﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.Skins;
using DevExpress.LookAndFeel;
using DevExpress.UserSkins;
using DevExpress.XtraBars;
using DevExpress.XtraBars.Ribbon;
using DevExpress.XtraBars.Helpers;
using VectorDraw.Professional.vdCollections;
using VectorDraw.Professional.vdPrimaries;
using VectorDraw.Professional.vdFigures;
using System.Threading;
using DevExpress.XtraCharts;
using VectorDraw.Geometry;
using VectorDraw.Professional.vdObjects;
using VectorDraw.Actions;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;
using System.Data.OracleClient;
using System.Collections;
using DevExpress.XtraTreeList.Nodes;
using DevExpress.XtraTreeList;
using Microsoft.Office.Interop;
using System.Reflection;
using CrystalDecisions.CrystalReports.Engine;


namespace PDNPAS
{
    public partial class MainForm : RibbonForm
    {

        private uint _PropertyName;
        private static DataTable userDataTable, authDataTable, menuDataTable, selectedMenuDataTable;
        private Hashtable htMenuState = new Hashtable(); //存放各菜单状态
        private Hashtable htMenuItem = new Hashtable(); //存放各菜单项
        private static string connectStr = "(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=210.35.88.92) (PORT=1521)))(CONNECT_DATA=(SERVICE_NAME=orcl)))";
        private static string connectUname = "pdnpasuser";
        private static string connectUpwd = "pdnpaspwd";


        private static DataTable dtLandArea = new DataTable("地块统计表");

        

        public MainForm()
        {          
            InitializeComponent();
            Thread.Sleep(3000);
            InitSkinGallery();
            InitAuthManageData();
            InitMenuState();
            testAuthMenu(StaticVariables.user.UserName);
            vdFC.BaseControl.vdDoubleClick += new VectorDraw.Professional.Control.DoubleClickEventHandler(BaseControl_vdDoubleClick);

        }
        void InitSkinGallery()
        {
            SkinHelper.InitSkinGallery(rgbiSkins, true);
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            tcgMain.SelectedTabPageIndex = 0;
            vdFC.BaseControl.ActiveDocument.Model.BkColorEx = Color.White;
            vdFC.BaseControl.ActiveDocument.Redraw(true);
            vdFC.UnLoadMenu();
            //vdFC.SetLayoutStyle(vdControls.vdFramedControl.LayoutStyle.PropertyGrid, false);

            StaticVariables.vdFC = vdFC;


        }

        private void iNew_ItemClick(object sender, ItemClickEventArgs e)
        {
            vdFC.CommandLine.ExecuteCommand("new");
            vdFC.BaseControl.ActiveDocument.Model.BkColorEx = Color.White;
            tcgMain.SelectedTabPageIndex = 0;
        }

        private void iOpen_ItemClick(object sender, ItemClickEventArgs e)
        {
            vdFC.CommandLine.ExecuteCommand("open");
            vdFC.BaseControl.ActiveDocument.Model.BkColorEx = Color.White;
            
            CreateModels();//创建变电站等图形块
        }

        private void iOpenS_ItemClick(object sender, ItemClickEventArgs e)
        {

        }

        private void iClose_ItemClick(object sender, ItemClickEventArgs e)
        {

        }

        private void iPrint_ItemClick(object sender, ItemClickEventArgs e)
        {

        }

        private void iSave_ItemClick(object sender, ItemClickEventArgs e)
        {
            vdFC.CommandLine.ExecuteCommand("save");
        }

        private void iSaveAs_ItemClick(object sender, ItemClickEventArgs e)
        {
            vdFC.CommandLine.ExecuteCommand("saveas");
        }

        private void iExit_ItemClick(object sender, ItemClickEventArgs e)
        {
            this.Close();
        }

        private void iCut_ItemClick(object sender, ItemClickEventArgs e)
        {
            vdFC.CommandLine.ExecuteCommand("clipcut");            
        }

        private void iCopy_ItemClick(object sender, ItemClickEventArgs e)
        {
            vdFC.CommandLine.ExecuteCommand("clipcopy");
        }

        private void iPaste_ItemClick(object sender, ItemClickEventArgs e)
        {
            vdFC.CommandLine.ExecuteCommand("clippaste");
        }

        private void iAll_ItemClick(object sender, ItemClickEventArgs e)
        {

        }

        private void iNone_ItemClick(object sender, ItemClickEventArgs e)//有待测试！！！！！！！！！！！！！！！！！！！！！！！！
        {
            vdSelection selset = vdFC.BaseControl.ActiveDocument.ActionUtility.getUserSelection();
            if (selset != null)
            {
                selset = null;
            }
            vdFC.BaseControl.ActiveDocument.Redraw(true);
        }

        private void iDel_ItemClick(object sender, ItemClickEventArgs e)
        {

        }

        private void iErase_ItemClick(object sender, ItemClickEventArgs e)
        {
            vdFC.CommandLine.ExecuteCommand("Erase");
        }

        private void iCopyModify_ItemClick(object sender, ItemClickEventArgs e)
        {
            vdFC.CommandLine.ExecuteCommand("Copy");
        }

        private void iMirror_ItemClick(object sender, ItemClickEventArgs e)
        {
            vdFC.CommandLine.ExecuteCommand("Mirror");
        }

        private void iOffset_ItemClick(object sender, ItemClickEventArgs e)
        {
            vdFC.CommandLine.ExecuteCommand("Offset");
        }

        private void iRectangularArray_ItemClick(object sender, ItemClickEventArgs e)
        {
            vdFC.CommandLine.ExecuteCommand("arrayrectangular");
        }

        private void iPolarArray_ItemClick(object sender, ItemClickEventArgs e)
        {
            vdFC.CommandLine.ExecuteCommand("arraypolar");
        }

        private void iMove_ItemClick(object sender, ItemClickEventArgs e)
        {
            vdFC.CommandLine.ExecuteCommand("Move");
        }

        private void iRotate_ItemClick(object sender, ItemClickEventArgs e)
        {
            vdFC.CommandLine.ExecuteCommand("Rotate");
        }

        private void iScale_ItemClick(object sender, ItemClickEventArgs e)
        {

        }

        private void iStretch_ItemClick(object sender, ItemClickEventArgs e)
        {
            vdFC.CommandLine.ExecuteCommand("Stretch");
        }

        private void iTrim_ItemClick(object sender, ItemClickEventArgs e)
        {
            vdFC.CommandLine.ExecuteCommand("Trim");
        }

        private void iExtend_ItemClick(object sender, ItemClickEventArgs e)
        {
            vdFC.CommandLine.ExecuteCommand("Extend");
        }

        private void iBreak_ItemClick(object sender, ItemClickEventArgs e)
        {
            vdFC.CommandLine.ExecuteCommand("Break");
        }

        private void iFillet_ItemClick(object sender, ItemClickEventArgs e)
        {
            vdFC.CommandLine.ExecuteCommand("Fillet");
        }

        private void iLine_ItemClick(object sender, ItemClickEventArgs e)
        {
            vdFC.CommandLine.ExecuteCommand("line");
        }

        private void iArc_ItemClick(object sender, ItemClickEventArgs e)
        {
            vdFC.CommandLine.ExecuteCommand("arc");
        }

        private void iCircle_ItemClick(object sender, ItemClickEventArgs e)
        {
            vdFC.CommandLine.ExecuteCommand("circle");
        }

        private void iEllipse_ItemClick(object sender, ItemClickEventArgs e)
        {
            vdFC.CommandLine.ExecuteCommand("ellipse");
        }

        private void iPolyline_ItemClick(object sender, ItemClickEventArgs e)
        {
            vdFC.CommandLine.ExecuteCommand("pl");
        }

        private void iRectangle_ItemClick(object sender, ItemClickEventArgs e)
        {
            vdFC.CommandLine.ExecuteCommand("rect");
        }

        private void iText_ItemClick(object sender, ItemClickEventArgs e)
        {
            vdFC.CommandLine.ExecuteCommand("text");
        }

        private void iMultitext_ItemClick(object sender, ItemClickEventArgs e)
        {
            vdFC.CommandLine.ExecuteCommand("mtext");
        }

        private void iPoint_ItemClick(object sender, ItemClickEventArgs e)
        {
            vdFC.CommandLine.ExecuteCommand("point");
        }

        private void iBhatch_ItemClick(object sender, ItemClickEventArgs e)
        {
            vdFC.CommandLine.ExecuteCommand("bhatch");
        }

        private void iImage_ItemClick(object sender, ItemClickEventArgs e)
        {
            vdFC.CommandLine.ExecuteCommand("image");
        }

        private void iXline_ItemClick(object sender, ItemClickEventArgs e)
        {

        }

        private void iXray_ItemClick(object sender, ItemClickEventArgs e)
        {

        }

        private void iLeader_ItemClick(object sender, ItemClickEventArgs e)
        {

        }

        private void iSpline_ItemClick(object sender, ItemClickEventArgs e)
        {

        }

        private void iWriteBlock_ItemClick(object sender, ItemClickEventArgs e)
        {
            vdFC.CommandLine.ExecuteCommand("writeblock");
          
        }

        private void iMakeBlock_ItemClick(object sender, ItemClickEventArgs e)
        {
            vdFC.CommandLine.ExecuteCommand("makeblock");
        }

        private void iInsertBlock_ItemClick(object sender, ItemClickEventArgs e)
        {
            vdFC.CommandLine.ExecuteCommand("insert");
        }

        private void iEditAttribute_ItemClick(object sender, ItemClickEventArgs e)
        {
            vdFC.CommandLine.ExecuteCommand("EditAttrib");
        }

        private void iAddAttribute_ItemClick(object sender, ItemClickEventArgs e)
        {
            vdFC.CommandLine.ExecuteCommand("addattribute");
        }

        private void iVertical_ItemClick(object sender, ItemClickEventArgs e)
        {
            vdFC.CommandLine.ExecuteCommand("DimRotatedVer");
        }

        private void iHorizontal_ItemClick(object sender, ItemClickEventArgs e)
        {
            vdFC.CommandLine.ExecuteCommand("DimRotatedHor");
        }

        private void iAutoRotated_ItemClick(object sender, ItemClickEventArgs e)
        {
            
        }

        private void iAligned_ItemClick(object sender, ItemClickEventArgs e)
        {
            vdFC.CommandLine.ExecuteCommand("DimAligned");
        }

        private void iAngular_ItemClick(object sender, ItemClickEventArgs e)
        {
            vdFC.CommandLine.ExecuteCommand("DimAngular");
        }

        private void iDiameter_ItemClick(object sender, ItemClickEventArgs e)
        {
            vdFC.CommandLine.ExecuteCommand("DimDiameter");
        }

        private void iRadial_ItemClick(object sender, ItemClickEventArgs e)
        {
            vdFC.CommandLine.ExecuteCommand("DimRadial");
        }

        private void iRedraw_ItemClick(object sender, ItemClickEventArgs e)
        {
            vdFC.CommandLine.ExecuteCommand("redraw");
        }

        private void iRegen_ItemClick(object sender, ItemClickEventArgs e)
        {

        }

        private void iZoomPrevious_ItemClick(object sender, ItemClickEventArgs e)
        {
            vdFC.CommandLine.ExecuteCommand("zp");
        }

        private void iZoomWindow_ItemClick(object sender, ItemClickEventArgs e)
        {
            vdFC.CommandLine.ExecuteCommand("zw");
        }

        private void iZoomIn_ItemClick(object sender, ItemClickEventArgs e)
        {
            vdFC.CommandLine.ExecuteCommand("zi");
        }

        private void iZoomOut_ItemClick(object sender, ItemClickEventArgs e)
        {
            vdFC.CommandLine.ExecuteCommand("zo");
        }

        private void iZoomAll_ItemClick(object sender, ItemClickEventArgs e)
        {
            vdFC.CommandLine.ExecuteCommand("za");
        }

        private void iZoomExtends_ItemClick(object sender, ItemClickEventArgs e)
        {
            vdFC.CommandLine.ExecuteCommand("ze");
        }

        private void iPan_ItemClick(object sender, ItemClickEventArgs e)
        {
            vdFC.CommandLine.ExecuteCommand("pan");
        }
        private void iLayers_ItemClick(object sender, ItemClickEventArgs e)
        {
            VectorDraw.Professional.Dialogs.LayersDialog.Show(vdFC.BaseControl.ActiveDocument);
        }

        private void iTextStyles_ItemClick(object sender, ItemClickEventArgs e)
        {
            VectorDraw.Professional.Dialogs.frmTextStyle.Show(vdFC.BaseControl.ActiveDocument);
        }

        private void iDimensionStyles_ItemClick(object sender, ItemClickEventArgs e)
        {
            VectorDraw.Professional.Dialogs.frmDimStyle.Show(vdFC.BaseControl.ActiveDocument);
        }

        private void iPointStyles_ItemClick(object sender, ItemClickEventArgs e)
        {
            VectorDraw.Professional.Dialogs.frmPointStyleDialog.Show(vdFC.BaseControl.ActiveDocument);
        }

        private void iExternalReferences_ItemClick(object sender, ItemClickEventArgs e)
        {
            VectorDraw.Professional.Dialogs.frmXrefManager.Show(vdFC.BaseControl.ActiveDocument);
        }

        private void iImageDefinitions_ItemClick(object sender, ItemClickEventArgs e)
        {
            VectorDraw.Professional.Dialogs.FrmImageDefs.Show(vdFC.BaseControl.ActiveDocument);
        }

        private void iLights_ItemClick(object sender, ItemClickEventArgs e)
        {
            VectorDraw.Professional.Dialogs.frmLightManager.Show(vdFC.BaseControl.ActiveDocument);
        }

        private void iOsnaps_ItemClick(object sender, ItemClickEventArgs e)
        {
            VectorDraw.Professional.vdObjects.vdDocument doc = vdFC.BaseControl.ActiveDocument;
            VectorDraw.Professional.Dialogs.OSnapDialog.Show(doc, doc.ActionControl);
        }



        private void iLandAnalysis_ItemClick(object sender, ItemClickEventArgs e)
        {
            OracleDBHelp oracleDB = new OracleDBHelp();
            //oracleDB.getTable("select * from \"TLoadDensity\" ");
           
            if (StaticVariables.loadDensityPlanNum == 0) 
            {
                MessageBox.Show("请先选择负荷密度方案");
                return;                
            }
            int planNum = StaticVariables.loadDensityPlanNum;//负荷密度方案为方案1
            DataTable loadDensityTable = oracleDB.getDataTable("select * from TLoadDensity ");

            tcgMain.SelectedTabPageIndex = 2;
            
            List<int> colorList =new List<int>();
            for (int i = 0; i < loadDensityTable.Rows.Count; i++)
            {
                if (!colorList.Contains(int.Parse(loadDensityTable.Rows[i][2].ToString())) && int.Parse(loadDensityTable.Rows[i][3].ToString())==planNum)
                {
                    colorList.Add(int.Parse(loadDensityTable.Rows[i][2].ToString()));
                    //MessageBox.Show(loadDensityTable.Rows[i][2].ToString());
                }
            }

            pgbBottom.EditValue = 10;

            //string str = "";
            int hatchNum = 0;
            //double area = 0;
            //开始扫描图层中的各地块hatch，把符合条件的地块收集起来
            StaticVariables.landList.Clear();
            for (int i = 0; i < vdFC.BaseControl.ActiveDocument.ActiveLayOut.Entities.Count; i++)
            {
                if (vdFC.BaseControl.ActiveDocument.ActiveLayOut.Entities[i] is vdPolyhatch)
                {
                    
                    vdPolyhatch hatch = (vdPolyhatch)vdFC.BaseControl.ActiveDocument.ActiveLayOut.Entities[i];
                    MyHatch myhatch = new MyHatch(hatch); 
                    if (hatch != null && colorList.Contains(myhatch.getColorIndex()+1))
                    {
                        hatchNum++;
                        int landPropID=0;
                        string landProp="";
                        
                        double plotRatio=0;
                        double loadDensityH=0;
                        double loadDensityL=0;
                        double simultaneity=0;
                        double secSimultaneity=0;
                        for (int j = 0; j < loadDensityTable.Rows.Count; j++)
                        {

                            if (int.Parse(loadDensityTable.Rows[j][3].ToString()) == planNum && int.Parse(loadDensityTable.Rows[j][2].ToString()) == (myhatch.getColorIndex() + 1))
                            {
                                landPropID = int.Parse(loadDensityTable.Rows[j][0].ToString());
                                landProp = loadDensityTable.Rows[j][1].ToString();
                                plotRatio = double.Parse(loadDensityTable.Rows[j][4].ToString());
                                loadDensityH = double.Parse(loadDensityTable.Rows[j][5].ToString());
                                loadDensityL = double.Parse(loadDensityTable.Rows[j][6].ToString());
                                simultaneity = double.Parse(loadDensityTable.Rows[j][7].ToString());
                                secSimultaneity = double.Parse(loadDensityTable.Rows[j][8].ToString());

                                break;
                            }
                        }

                        Land land = new Land(landPropID, hatch.ToMesh(0).Area(), myhatch, landProp, 
                            myhatch.getColorIndex() + 1, planNum, plotRatio, loadDensityH, loadDensityL, simultaneity, secSimultaneity );
                        StaticVariables.landList.Add(land);
                    }
                }
                
            }

            pgbBottom.EditValue = 20;

            ////统计特殊的hatch，被解析为：ployline
            //List<vdPolyline> plineList = new List<vdPolyline>();
            //for (int i = 0; i < vdFC.BaseControl.ActiveDocument.ActiveLayOut.Entities.Count; i++)
            //{
            //    if (vdFC.BaseControl.ActiveDocument.ActiveLayOut.Entities[i] is vdPolyline)
            //    {
            //        vdPolyline pline = (vdPolyline)vdFC.BaseControl.ActiveDocument.ActiveLayOut.Entities[i];
            //        if (pline != null && pline.HatchProperties != null && pline.HatchProperties.FillMode == VectorDraw.Professional.Constants.VdConstFill.VdFillModeSolid)
            //        {
            //            MyPLine mypline = new MyPLine(pline);
                        
            //            if (colorList.Contains(mypline.getColorIndex() + 1) &&pline.Flag==VectorDraw.Professional.Constants.VdConstPlineFlag.PlFlagCLOSE)//满足颜色要求和封闭的要求
            //            {
            //                plineList.Add(pline);
            //            }
            //        }
            //    }
            //}
            //vdFC.BaseControl.ActiveDocument.Redraw(true);
            ////MessageBox.Show("符合条件的pline数量为："+plineList.Count);

            //对地块进行排序，从上到下，从左到右。
            //students.Sort(delegate(Student a, Student b) { return a.Age.CompareTo(b.Age); });
            StaticVariables.landList.Sort(delegate(Land landA, Land landB)
            {
                if (landB.Myhatch.Hatch.BoundingBox.UpperLeft.y.CompareTo(landA.Myhatch.Hatch.BoundingBox.UpperLeft.y)!=0)
                    return landB.Myhatch.Hatch.BoundingBox.UpperLeft.y.CompareTo(landA.Myhatch.Hatch.BoundingBox.UpperLeft.y);
                else
                    return landA.Myhatch.Hatch.BoundingBox.UpperLeft.x.CompareTo(landB.Myhatch.Hatch.BoundingBox.UpperLeft.x);
            });

            //对地块从上到下，从左到右编号,并计算负荷
            for (int i = 1; i < StaticVariables.landList.Count+1; i++)
            {
                string landID = "";
                if (i < 10)
                {
                    landID += "A-00";
                    StaticVariables.landList[i-1].LandID = landID + i.ToString();
                }
                else if (i < 100)
                {
                    landID += "A-0";
                    StaticVariables.landList[i-1].LandID = landID + i.ToString();
                }
                else if(i<1000)
                {
                    landID += "A-";
                    StaticVariables.landList[i-1].LandID = landID + i.ToString();
                }
                else
                {
                    MessageBox.Show("地块超过1000块，请将大区域适当划分！");
                    return;
                }

                //计算负荷
                StaticVariables.landList[i-1].calculateLoad();

               
            }


            pgbBottom.EditValue = 40;


            //将相同性质的地块合并，并生成详细的地块统计信息
            StaticVariables.landCollectionList.Clear();
            for (int i = 0; i < StaticVariables.landList.Count;i++ )
            {
                int flag = 0;//表示不包含相同性质的地块
                int index = -1;//存放相同性质地块的index值
                for (int j = 0; j < StaticVariables.landCollectionList.Count; j++)
                {
                    if (StaticVariables.landCollectionList[j].LandPropID == StaticVariables.landList[i].LandPropID)
                    {
                        flag = 1; index = j; break;
                    }
                }
                if (flag == 1)
                {
                    StaticVariables.landCollectionList[index].LandArea += StaticVariables.landList[i].LandArea;
                    StaticVariables.landCollectionList[index].LandLoadH += StaticVariables.landList[i].LandLoadH;                 
                    StaticVariables.landCollectionList[index].LID++;//这里将LID暂时当做计数用
                }
                else
                {
                    Land land = StaticVariables.landList[i].myClone();
                    land.LID = 1;
                    StaticVariables.landCollectionList.Add(land);
                }
            }

            //MessageBox.Show("用地性质类型有："+StaticVariables.landCollectionList.Count.ToString());

            //在grid control 中显示
            dtLandArea.Columns.Clear();
            dtLandArea.Columns.Add("landProp", typeof(string));
            dtLandArea.Columns.Add("landArea", typeof(double));
            dtLandArea.Columns.Add("plotRatio", typeof(double));
            dtLandArea.Columns.Add("floorArea", typeof(double));
            dtLandArea.Columns.Add("landColor", typeof(int));
            dtLandArea.Columns.Add("landNum", typeof(int));//
            dtLandArea.Columns.Add("landAreaCheckA", typeof(double));

            for (int i = 0; i < StaticVariables.landCollectionList.Count; i++)
            {
                Land land = new Land();
                land = StaticVariables.landCollectionList[i];
                dtLandArea.Rows.Add(new object[] { land.LandProp, land.LandArea, land.PlotRatio, land.LandArea * land.PlotRatio, land.LandColor, land.LID, land.LandArea });
            }

            gcLand.DataSource = dtLandArea;
            pgbBottom.EditValue = 100;
            MessageBox.Show("解析地块成功！");
            pgbBottom.EditValue = 0;
        }

        private void iDensityPlan_ItemClick(object sender, ItemClickEventArgs e)
        {
            tcgMain.SelectedTabPageIndex = 2;
            tabLoadForecast.SelectedTabPageIndex = 0;
            cmbDensityPlan.Properties.Items.Clear();
            cmbDensityPlan.Focus();

            //从数据库负荷密度方案表中获取方案名称
            for (int i = 0; i < 1; i++)
            {
                cmbDensityPlan.Properties.Items.Add("浙江省宁波市鄞州区集仕港");
            }
        }

        private void cmbDensityPlan_SelectedIndexChanged(object sender, EventArgs e)
        {
            //根据数据库负荷密度方案名称确定负荷密度方案编号
            StaticVariables.loadDensityPlanNum = 1;
        }

        private void iLandNum_ItemClick(object sender, ItemClickEventArgs e)
        {

            tcgMain.SelectedTabPageIndex = 0;
            
            //show mtext in each hatch

            //create a new vdLayer with name "L地块编号" and make it as active. 
            vdLayer activelayer = vdFC.BaseControl.ActiveDocument.ActiveLayer;

            vdLayer vdlayer = vdFC.BaseControl.ActiveDocument.Layers.FindName("L地块编号");
            if (vdlayer == null)
            {
                vdLayer layer = vdFC.BaseControl.ActiveDocument.Layers.Add("L地块编号");
                layer.SetUnRegisterDocument(vdFC.BaseControl.ActiveDocument);
                layer.setDocumentDefaults();
                vdFC.BaseControl.ActiveDocument.ActiveLayer = layer;
            }
            else
            {
                vdFC.BaseControl.ActiveDocument.ActiveLayer = vdlayer;
            }

            for (int i = 0; i < StaticVariables.landList.Count; i++)
            {
                if (StaticVariables.landList[i].LoadDensityH > 5)
                {
                    vdMText oneMtext = new vdMText();
                    //We set the document where the Mtext is going to be added. This is important
                    //for the vdMText in order to obtain initial properties with setDocumentDefaults.
                    oneMtext.SetUnRegisterDocument(vdFC.BaseControl.ActiveDocument);
                    oneMtext.setDocumentDefaults();
                    //Now we will change some properties of the text.
                    oneMtext.InsertionPoint = StaticMethods.GetHatchCentroid(StaticVariables.landList[i].Myhatch.Hatch);//StaticVariables.landList[i].Myhatch.Hatch.BoundingBox.MidPoint;//插入点坐标

                    oneMtext.HorJustify = VectorDraw.Professional.Constants.VdConstHorJust.VdTextHorCenter;
                    oneMtext.Height = 8;
                    //The Text string can contain some special control characters like "\P" or "\C1" which
                    // control the way that this multiLine text is going to be displayed.
                    oneMtext.TextString = StaticVariables.landList[i].LandID + @"\P" + StaticVariables.landList[i].LandProp;//+ @"\P" +StaticVariables.landList[i].LandArea.ToString("0.0");
                    //Now we will add this object to the Entities collection of the Model Layout(ActiveLayout).
                    vdFC.BaseControl.ActiveDocument.ActiveLayOut.Entities.AddItem(oneMtext);
                }

            }
            vdFC.BaseControl.ActiveDocument.Redraw(true);

            vdFC.BaseControl.ActiveDocument.ActiveLayer = activelayer;
        }

        private void iLoadForecast_ItemClick(object sender, ItemClickEventArgs e)
        {

            tcgMain.SelectedTabPageIndex = 0;


            //create a new vdLayer with name "L预测负荷" and make it as active. 
            vdLayer activelayer = vdFC.BaseControl.ActiveDocument.ActiveLayer;

            vdLayer vdlayer = vdFC.BaseControl.ActiveDocument.Layers.FindName("L预测负荷");
            if (vdlayer == null)
            {

                vdLayer layer = vdFC.BaseControl.ActiveDocument.Layers.Add("L预测负荷");
                layer.SetUnRegisterDocument(vdFC.BaseControl.ActiveDocument);
                layer.setDocumentDefaults();
                vdFC.BaseControl.ActiveDocument.ActiveLayer = layer;
            }
            else
            {
                vdFC.BaseControl.ActiveDocument.ActiveLayer = vdlayer;
            }

            for (int i = 0; i < StaticVariables.landList.Count; i++)
            {
                if (StaticVariables.landList[i].LoadDensityH > 5)
                {
                    vdMText oneMtext = new vdMText();
                    //We set the document where the Mtext is going to be added. This is important
                    //for the vdMText in order to obtain initial properties with setDocumentDefaults.
                    oneMtext.SetUnRegisterDocument(vdFC.BaseControl.ActiveDocument);
                    oneMtext.setDocumentDefaults();
                    //Now we will change some properties of the text.
                    oneMtext.InsertionPoint = StaticMethods.GetHatchCentroid(StaticVariables.landList[i].Myhatch.Hatch);//StaticVariables.landList[i].Myhatch.Hatch.BoundingBox.MidPoint;//插入点坐标
                    //oneMtext.InsertionPoint =  oneMtext.InsertionPoint = StaticMethods.GetHatchCentroid(StaticVariables.landList[i].Myhatch.Hatch);//StaticVariables.landList[i].Myhatch.Hatch.BoundingBox.MidPoint;//插入点坐标StaticVariables.landList[i].Myhatch.Hatch.BoundingBox.MidPoint;//插入点坐标
                    oneMtext.HorJustify = VectorDraw.Professional.Constants.VdConstHorJust.VdTextHorCenter;
                    oneMtext.Height = 8;
                    //The Text string can contain some special control characters like "\P" or "\C1" which
                    // control the way that this multiLine text is going to be displayed.
                    oneMtext.TextString = @"\P" + @"\P" + (StaticVariables.landList[i].LandLoadM * StaticVariables.landList[i].AreaCheckCoef/1000000.0).ToString("0.0")+"MW";// StaticVariables.landList[i].LandID +    // + StaticVariables.landList[i].LandProp
                    //Now we will add this object to the Entities collection of the Model Layout(ActiveLayout).
                    vdFC.BaseControl.ActiveDocument.ActiveLayOut.Entities.AddItem(oneMtext);
                }

            }
            vdFC.BaseControl.ActiveDocument.Redraw(true);

            vdFC.BaseControl.ActiveDocument.ActiveLayer = activelayer;
        }


        private void spinYear_EditValueChanged(object sender, EventArgs e)
        {
            StaticVariables.loadOfYear.Columns.Clear();
            StaticVariables.loadOfYear.Rows.Clear();
            StaticVariables.loadOfYear.Columns.Add("year", typeof(int));
            StaticVariables.loadOfYear.Columns.Add("load", typeof(double));
            int startyear = (int)spinStartYear.Value;
            int endyear = (int)spinEndYear.Value;
            for (int i = startyear; i <= endyear; i++)
            {
                StaticVariables.loadOfYear.Rows.Add(new object[] { i, 0 });
            }

            gcLinearRegression.DataSource = StaticVariables.loadOfYear;
        }

        private void iHistoryLoad_ItemClick(object sender, ItemClickEventArgs e)
        {
            tcgMain.SelectedTabPageIndex = 2;
            tabLoadForecast.SelectedTabPageIndex = 2;
            spinStartYear.Focus();

            StaticVariables.loadOfYear.Columns.Clear();
            StaticVariables.loadOfYear.Rows.Clear();
            StaticVariables.loadOfYear.Columns.Add("year", typeof(int));
            StaticVariables.loadOfYear.Columns.Add("load", typeof(double));
            int startyear = (int)spinStartYear.Value;
            int endyear = (int)spinEndYear.Value;
            for (int i = startyear; i <= endyear; i++)
            {
                StaticVariables.loadOfYear.Rows.Add(new object[] { i, 0 });
            }
            gcLinearRegression.DataSource = StaticVariables.loadOfYear;
        }

        private void btnLinearRegression_Click(object sender, EventArgs e)
        {

            StaticMethods.GetLinearRegressionCoeffficient(StaticVariables.loadOfYear,out StaticVariables.a,out StaticVariables.b);
            txtA.Text = StaticVariables.a.ToString("0.00"); 
            txtB.Text = StaticVariables.b.ToString("0.00");
            
            //根据线性回归线，获得未来5年的预测负荷值
            int n = StaticVariables.loadOfYear.Rows.Count;
            int firstYear = Convert.ToInt32(StaticVariables.loadOfYear.Rows[0].ItemArray[0]);
            int lastYear = Convert.ToInt32(StaticVariables.loadOfYear.Rows[n-1].ItemArray[0]);
            DataTable dtLoadForecast = new DataTable();
            dtLoadForecast.Columns.Clear();
            dtLoadForecast.Rows.Clear();
            dtLoadForecast.Columns.Add("year", typeof(int));
            dtLoadForecast.Columns.Add("load", typeof(double));
            dtLoadForecast.Rows.Add(new object[] { firstYear, StaticVariables.b * firstYear + StaticVariables.a });
            for (int i = lastYear+1; i <= lastYear+5; i++)
            {
                dtLoadForecast.Rows.Add(new object[] { i, StaticVariables.b * i + StaticVariables.a });
            }
            
            
            //生成图表
            
            chartHistoryLoad.Series.Clear();
            //定义线型，名称
            Series S1 = new Series("线性回归线", ViewType.Line);
            //定义X轴的数据的类型。质量，数字，时间
            S1.ArgumentScaleType = ScaleType.Numerical;
            //定义线条上点的标识形状
            ((LineSeriesView)S1.View).LineMarkerOptions.Kind = MarkerKind.Circle;
            //线条的类型，虚线，实线
            ((LineSeriesView)S1.View).LineStyle.DashStyle = DashStyle.Solid;
            //S1绑定数据源
            S1.DataSource = dtLoadForecast;
            //S1的X轴数据源字段
            S1.ArgumentDataMember = "year";
            //S2的Y轴数据源字段
            S1.ValueDataMembers[0] = "load";
            //点状图演示
            Series S2 = new Series("历史负荷数据", ViewType.Point);
            S2.ArgumentScaleType = ScaleType.Numerical;
            S2.DataSource = StaticVariables.loadOfYear;
            S2.ArgumentDataMember = "year";
            S2.ValueDataMembers[0] = "load";

            //加入chartcontrol
            chartHistoryLoad.Series.Add(S1);
            chartHistoryLoad.Series.Add(S2);
           

            //定义chart标题
            ChartTitle CT1 = new ChartTitle();
            CT1.Text = "线性回归法";
            ChartTitle CT2 = new ChartTitle();
            CT2.Text = "负荷预测";
            CT2.TextColor = System.Drawing.Color.Black;
            CT2.Font = new Font("Tahoma", 8);
            //标题对齐方式
            CT2.Dock = ChartTitleDockStyle.Bottom;
            CT2.Alignment = StringAlignment.Far;
            chartHistoryLoad.Titles.Clear();
            chartHistoryLoad.Titles.Add(CT1);
            chartHistoryLoad.Titles.Add(CT2);
            CT2.Indent = 1;
            //坐标标题的定义
            //坐标值说明的字体尺寸，颜色定义
            ((XYDiagram)chartHistoryLoad.Diagram).AxisY.Title.Font = new Font("Tahoma", 10);
            ((XYDiagram)chartHistoryLoad.Diagram).AxisY.Title.TextColor = System.Drawing.Color.Blue;
            ((XYDiagram)chartHistoryLoad.Diagram).AxisY.Title.Text = "负荷(单位：瓦)";
            ((XYDiagram)chartHistoryLoad.Diagram).AxisY.Title.Visible = true;
            ((XYDiagram)chartHistoryLoad.Diagram).AxisX.Title.Text = "年份";
            ((XYDiagram)chartHistoryLoad.Diagram).AxisX.Title.TextColor = System.Drawing.Color.Blue;
            ((XYDiagram)chartHistoryLoad.Diagram).AxisX.Title.Visible = true;
            XYDiagram DiagramOwn = (XYDiagram)chartHistoryLoad.Diagram;
            //图例的位置定义
            chartHistoryLoad.Legend.AlignmentHorizontal = LegendAlignmentHorizontal.Right;
            chartHistoryLoad.Legend.AlignmentVertical = LegendAlignmentVertical.Bottom;

        }

        private void iDensityCheck_ItemClick(object sender, ItemClickEventArgs e)
        {
            rdoResultCheck.SelectedIndex = 0;
        }

        private void iRegressionCheck_ItemClick(object sender, ItemClickEventArgs e)
        {
            rdoResultCheck.SelectedIndex = 1;
        }

        private void btnCheckLoadForecast_Click(object sender, EventArgs e)
        {
            if (txtCurrentLoad.Text == "" || txtCurrentLoad.Text == "")
            {
                MessageBox.Show("请输入现状负荷！");
                return;
            }
            DateTime currentTime =DateTime.Now;
            int currentYear = currentTime.Year;
            int saturationYear = 2020;//读取数据库，数据库中默认值为2020，用户可以修改。
            double currentLoad=double.Parse( txtCurrentLoad.Text);
            double futureLoad=double.Parse(txtFutureLoad.Text);
            int n = saturationYear - currentYear;
     
            double avgRate = Math.Pow(futureLoad/currentLoad,1.0/n)-1;
            if (avgRate < 0.2 && avgRate > 0.06)
            {
                MessageBox.Show("负荷平均增长率为" + (avgRate * 100).ToString("0.00") + "%,在6%与20%之间，负荷预测结果合理！");
            }
            else 
            {
                MessageBox.Show("负荷平均增长率为" + (avgRate * 100).ToString("0.00") + "%,不在6%与20%之间，负荷预测结果不合理！");
            }
        }

        private void rdoResultCheck_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (rdoResultCheck.SelectedIndex == 0)
            {
                //double saturationLoad = 0.00;
                //for (int i = 0; i < StaticVariables.landList.Count; i++)
                //{
                //    saturationLoad += StaticVariables.landList[i].LandLoadM;
                
                //}
                //double secSimultaneity=0.8;
                //saturationLoad = saturationLoad* secSimultaneity;
                //txtFutureLoad.Text = saturationLoad.ToString("0.00");
                txtFutureLoad.Text = txtLoadTotal.Text;
            }
            else if (rdoResultCheck.SelectedIndex == 1)
            {
                int saturationYear = 2020;//读取数据库，数据库中默认值为2020，用户可以修改。
                double saturationLoad = saturationYear * StaticVariables.b + StaticVariables.a;
                txtFutureLoad.Text = saturationLoad.ToString("0.00");
            }
            else
            { }
        }

        public void statistics()
        {
            //transline
            DataTable dt = new DataTable("线路工程统计");
            dt.Columns.Add("ID", typeof(int));
            dt.Columns.Add("translineID", typeof(string));
            dt.Columns.Add("translineType", typeof(string));
            dt.Columns.Add("translineLen", typeof(double));
            dt.Columns.Add("startP", typeof(string));
            dt.Columns.Add("endP", typeof(string));
            dt.Columns.Add("translineLoad", typeof(double));
            dt.Columns.Add("lineStandardUnitID", typeof(int));
            for (int i = 0; i < StaticVariables.translineList.Count; i++)
            {
                Transline line = new Transline();
                line = StaticVariables.translineList[i];
                dt.Rows.Add(new object[] { i+1,new string( line.TranslineID), line.TranslineType, line.TranslineLen, StaticMethods.GetStNameByControlNum(line.StartP,StaticVariables.substationList,StaticVariables.switchStationList,StaticVariables.loopstationList),
                    StaticMethods.GetStNameByControlNum(line.EndP,StaticVariables.substationList,StaticVariables.switchStationList,StaticVariables.loopstationList), line.Load, line.StandardUnitID});
            }
            MessageBox.Show("线路的标准单元编号为："+StaticVariables.translineList[0].StandardUnitID);
            gcTransline.DataSource = dt;

            //loopst
            DataTable dtLoopst = new DataTable("环网站工程统计");
            dtLoopst.Columns.Add("loopstationID", typeof(int));
            dtLoopst.Columns.Add("loopstName", typeof(string));
            dtLoopst.Columns.Add("loopstX", typeof(double));
            dtLoopst.Columns.Add("loopstY", typeof(double));
            dtLoopst.Columns.Add("loopstType", typeof(string));
            dtLoopst.Columns.Add("voltageLevel", typeof(int));
            dtLoopst.Columns.Add("loopstLoad", typeof(double));
            dtLoopst.Columns.Add("loopstCapacity", typeof(double));
            dtLoopst.Columns.Add("loopstStandardUnitTID", typeof(int));
            for (int i = 0; i < StaticVariables.loopstationList.Count; i++)
            {
                Loopstation loopst = new Loopstation();
                loopst = StaticVariables.loopstationList[i];
                dtLoopst.Rows.Add(new object[] { i+1, loopst.LoopstName, loopst.LoopstX, loopst.LoopstY, loopst.LoopstType,
                    loopst.VoltageLevel, loopst.Load, loopst.Capacity,loopst.StandardUnitTID});
            }
            gcLoopstation.DataSource = dtLoopst;


            //switchSt
            DataTable dtSwitchSt = new DataTable("开关站工程统计");
            dtSwitchSt.Columns.Add("switchStID", typeof(int));
            dtSwitchSt.Columns.Add("switchStName", typeof(string));
            dtSwitchSt.Columns.Add("switchStX", typeof(double));
            dtSwitchSt.Columns.Add("switchStY", typeof(double));
            dtSwitchSt.Columns.Add("switchStType", typeof(string));
            dtSwitchSt.Columns.Add("switchStVoltageLevel", typeof(int));
            dtSwitchSt.Columns.Add("switchStLoad", typeof(double));
            dtSwitchSt.Columns.Add("switchStCapacity", typeof(double));
            dtSwitchSt.Columns.Add("switchStStandardUnitTID", typeof(int));
            for (int i = 0; i < StaticVariables.switchStationList.Count; i++)
            {
                SwitchStation switchSt = new SwitchStation();
                switchSt = StaticVariables.switchStationList[i];
                dtSwitchSt.Rows.Add(new object[] { i+1, switchSt.SwitchStName, switchSt.SwitchStX, switchSt.SwitchStY, switchSt.SwitchStType,
                    switchSt.VoltageLevel, switchSt.Load, switchSt.Capacity,switchSt.StandardUnitTID});
            }
            gcSwitchStation.DataSource = dtSwitchSt;


            //subst
            DataTable dtSubSt = new DataTable("变电站工程统计");
            dtSubSt.Columns.Add("subStID", typeof(int));
            dtSubSt.Columns.Add("subStName", typeof(string));
            dtSubSt.Columns.Add("subStType", typeof(string));
            dtSubSt.Columns.Add("subStX", typeof(double));
            dtSubSt.Columns.Add("subStY", typeof(double));
            dtSubSt.Columns.Add("subStIVoltageLevel", typeof(int));
            dtSubSt.Columns.Add("subStOVoltageLevel", typeof(int));
            dtSubSt.Columns.Add("transfNum", typeof(int));
            dtSubSt.Columns.Add("subStCapacity", typeof(double));
            dtSubSt.Columns.Add("subStLoad", typeof(double));
            dtSubSt.Columns.Add("intervalNum", typeof(int));
            for (int i = 0; i < StaticVariables.substationList.Count; i++)
            {
                Substation subst = new Substation();
                subst = StaticVariables.substationList[i];
                dtSubSt.Rows.Add(new object[] { i+1, subst.SubstName, subst.SubstType,subst.SubstX,subst.SubstY,subst.IVoltageLevel,subst.OVoltageLevel,
                    subst.TransfNum,subst.Capacity,subst.Load,subst.IntervalNum});
            }
            gcSubstation.DataSource = dtSubSt;
            

            //standardUnit
            DataTable dtStandardUnit = new DataTable("标准单元工程统计");
            dtStandardUnit.Columns.Add("standardUnitID", typeof(int));
            dtStandardUnit.Columns.Add("loopstNum", typeof(int));
            dtStandardUnit.Columns.Add("standardUnitLoad", typeof(double));

            for (int i = 0; i < StaticVariables.standardUnitList.Count; i++)
            {
                StandardUnit standardUnit = new StandardUnit();
                standardUnit = StaticVariables.standardUnitList[i];
                dtStandardUnit.Rows.Add(new object[] { i+1, standardUnit.LoopstationList.Count, standardUnit.GetLoad() });
            }
            gcStandardUnit.DataSource = dtStandardUnit;


            StaticVariables.excelDS.Tables.Add(dt);
            StaticVariables.excelDS.Tables.Add(dtLoopst);
            StaticVariables.excelDS.Tables.Add(dtSwitchSt);
            StaticVariables.excelDS.Tables.Add(dtSubSt);
            StaticVariables.excelDS.Tables.Add(dtStandardUnit);

        }

        private void btnTest_Click(object sender, EventArgs e)
        {
            statistics();
        }

        private void chkPropertyGrid_CheckedChanged(object sender, ItemClickEventArgs e)
        {
            if(chkPropertyGrid.Checked)
            {
                vdFC.SetLayoutStyle(vdControls.vdFramedControl.LayoutStyle.PropertyGrid, true);
            }
            else
            {
                vdFC.SetLayoutStyle(vdControls.vdFramedControl.LayoutStyle.PropertyGrid, false);
            }
        }

        private void chkCommandLine_CheckedChanged(object sender, ItemClickEventArgs e)
        {
            if (chkCommandLine.Checked)
            {
                vdFC.SetLayoutStyle(vdControls.vdFramedControl.LayoutStyle.CommandLine, true);
            }
            else
            {
                vdFC.SetLayoutStyle(vdControls.vdFramedControl.LayoutStyle.CommandLine, false);
            }
        }

        private void chkStatusBar_CheckedChanged(object sender, ItemClickEventArgs e)
        {
            if (chkStatusBar.Checked)
            {
                vdFC.SetLayoutStyle(vdControls.vdFramedControl.LayoutStyle.StatusBar, true);
            }
            else
            {
                vdFC.SetLayoutStyle(vdControls.vdFramedControl.LayoutStyle.StatusBar, false);
            }
        }

        private void iInvestEsti_ItemClick(object sender, ItemClickEventArgs e)
        {
            tcgMain.SelectedTabPageIndex = 4;
            tabEvaluation.SelectedTabPageIndex = 5;
            InvestEsti();
        }
        void InvestEsti()
        {

            //InvestEsti
            DataTable dtInvestment = new DataTable("投资费用");
            dtInvestment.Columns.Add("investID", typeof(int));
            dtInvestment.Columns.Add("equipmentKind", typeof(string));
            dtInvestment.Columns.Add("equipmentType", typeof(string));
            dtInvestment.Columns.Add("equipmentNum", typeof(double));
            dtInvestment.Columns.Add("price", typeof(double));
            dtInvestment.Columns.Add("cost", typeof(double));

            int rowNum = 1;

            double switchStPrice = 1000;//需要从数据库表格中读取价格数据
            int switchStNum = StaticVariables.switchStationList.Count;
            if (switchStNum > 0)
            {
                dtInvestment.Rows.Add(new object[] { rowNum, "开关站", StaticVariables.switchStationList[0].SwitchStType, switchStNum, switchStPrice, switchStNum * switchStPrice });
                rowNum++;
            }

            double loopStPrice = 1500;//需要从数据库中读取数据
            int loopStNum = StaticVariables.loopstationList.Count;
            if (loopStNum > 0)
            {
                dtInvestment.Rows.Add(new object[] { rowNum, "环网站", StaticVariables.loopstationList[0].LoopstType, loopStNum, loopStPrice, loopStNum * loopStPrice });
                rowNum++;
            }

            double lineLength1 = 0;
            double lineLength2 = 0;
            double lineLength3 = 0;
            double linePrice1 = 400;//需要从数据库中读取数据
            double linePrice2 = 500;
            double linePrice3 = 600;
            for (int i = 0; i < StaticVariables.translineList.Count; i++)
            {
                Transline line = new Transline();
                line = StaticVariables.translineList[i];
                if (line.TranslineTypeID == 1)
                {
                    lineLength1 += line.TranslineLen;
                }
                else if (line.TranslineTypeID == 2)
                {
                    lineLength2 += line.TranslineLen;
                }
                else if (line.TranslineTypeID == 3)
                {
                    lineLength3 += line.TranslineLen;
                }
                else { }

            }
            dtInvestment.Rows.Add(new object[] { rowNum, "输电线", "YJV22_3_300", lineLength1.ToString("0.00"), linePrice1, (lineLength1 * linePrice1)}); //JKLYJ_10_185, 
            rowNum++;
            dtInvestment.Rows.Add(new object[] { rowNum, "输电线", "JKLYJ_10_185", lineLength2.ToString("0.00"), linePrice2, lineLength2 * linePrice2 }); //, VLV22
            rowNum++;
            dtInvestment.Rows.Add(new object[] { rowNum, "输电线", "VLV22", lineLength3.ToString("0.00"), linePrice3, lineLength3 * linePrice3 }); //JKLYJ_10_185, VLV22
            rowNum++;

            gcInvestEsti.DataSource = dtInvestment;  
        
        }

        private void iAddSubstation_ItemClick(object sender, ItemClickEventArgs e)
        {
            if (vdFC.BaseControl.ActiveDocument.Blocks.FindName("MySubstationModel") == null)
            {
                MessageBox.Show("变电站模型未定义！");
                return;
            }

            tcgMain.SelectedTabPageIndex = 0;
            

            vdInsert ins = new vdInsert();
            ins.SetUnRegisterDocument(vdFC.BaseControl.ActiveDocument);
            ins.setDocumentDefaults();
            ins.Block = vdFC.BaseControl.ActiveDocument.Blocks.FindName("MySubstationModel");
            //获取变电站的位置
            gPoint userpoint;
            vdFC.BaseControl.ActiveDocument.Prompt("请输入变电站地址：");
            //The user can either click a point or type at the command line a point like 5,5,2
            StatusCode ret = vdFC.BaseControl.ActiveDocument.ActionUtility.getUserPoint(out userpoint);
            //MessageBox.Show("userpoint" + userpoint.x.ToString("0.00") + "，" + userpoint.y.ToString("0,00"));
            vdFC.BaseControl.ActiveDocument.Prompt(null);
            if (ret == StatusCode.Success)
            {
                ins.InsertionPoint = userpoint;
            }
            ins.CreateDefaultAttributes();
            if (ins.Attributes.Count == 1)
                ins.Attributes[0].ValueString = "新建变电站";


            ins.Xscale = 50;
            ins.Yscale = 50;
            vdFC.BaseControl.ActiveDocument.Model.Entities.AddItem(ins);
            vdFC.BaseControl.ActiveDocument.Redraw(true);
            //MessageBox.Show("ins.InsertionPoint" + ins.InsertionPoint.x.ToString("0.00") + "，" + ins.InsertionPoint.y.ToString("0,00"));
            Substation substation = new Substation("新建变电站",ins.InsertionPoint.x,ins.InsertionPoint.y,0,0,ins.Block,ins);
            StaticVariables.substationList.Add(substation);

            //vdXProperty propName = ins.Block.XProperties.FindName("变电站名称");
            //propName.PropValue = "新建变电站";

        }

        void CreateModels()
        { 
            //生成变电站块
            vdBlock blkSubstation = new vdBlock();
            blkSubstation.SetUnRegisterDocument(vdFC.BaseControl.ActiveDocument);
            blkSubstation.setDocumentDefaults();

            vdPolyline pline = new vdPolyline();
            pline.SetUnRegisterDocument(vdFC.BaseControl.ActiveDocument);
            pline.setDocumentDefaults();
            pline.VertexList.Add(new gPoint(1, 1));
            pline.VertexList.Add(new gPoint(1, -1));
            pline.VertexList.Add(new gPoint(-1, -1));
            pline.VertexList.Add(new gPoint(-1, 1));
            pline.VertexList.Add(new gPoint(1, 1));
            blkSubstation.Entities.AddItem(pline);

            pline = new vdPolyline();
            pline.SetUnRegisterDocument(vdFC.BaseControl.ActiveDocument);
            pline.setDocumentDefaults();
            pline.VertexList.Add(new gPoint(1.2, 1.2));
            pline.VertexList.Add(new gPoint(1.2, -1.2));
            pline.VertexList.Add(new gPoint(-1.2, -1.2));
            pline.VertexList.Add(new gPoint(-1.2, 1.2));
            pline.VertexList.Add(new gPoint(1.2, 1.2));
            blkSubstation.Entities.AddItem(pline);

            pline = new vdPolyline();
            pline.SetUnRegisterDocument(vdFC.BaseControl.ActiveDocument);
            pline.setDocumentDefaults();
            pline.VertexList.Add(new gPoint(1.4, 1.4));
            pline.VertexList.Add(new gPoint(1.4, -1.4));
            pline.VertexList.Add(new gPoint(-1.4, -1.4));
            pline.VertexList.Add(new gPoint(-1.4, 1.4));
            pline.VertexList.Add(new gPoint(1.4, 1.4));
            blkSubstation.Entities.AddItem(pline);

            vdCircle cir = new vdCircle();
            cir.SetUnRegisterDocument(vdFC.BaseControl.ActiveDocument);
            cir.setDocumentDefaults();
            cir.Center = new gPoint(0,0);
            cir.Radius = 0.8;
            blkSubstation.Entities.AddItem(cir);

            blkSubstation.Origin = new gPoint(0,0);
            blkSubstation.Name = "MySubstationModel";

            vdAttribDef attribdef = new vdAttribDef();
            attribdef.SetUnRegisterDocument(vdFC.BaseControl.ActiveDocument);
            attribdef.setDocumentDefaults();
            attribdef.InsertionPoint = new gPoint(-1.6, 1.6);
            attribdef.TagString = "SubstationName";
            attribdef.ValueString = "变电站0";
            blkSubstation.Entities.AddItem(attribdef);

            //vdText substName = new vdText();
            //substName.SetUnRegisterDocument(vdFC.BaseControl.ActiveDocument);
            //substName.setDocumentDefaults();
            //substName.TextString = "变电站0";
            //substName.Label = "变电站名称";
            //substName.InsertionPoint = new gPoint(0,2.2);
            //blkSubstation.Entities.AddItem(substName);

            //vdText substCapacity = new vdText();
            //substCapacity.SetUnRegisterDocument(vdFC.BaseControl.ActiveDocument);
            //substCapacity.setDocumentDefaults();
            //substCapacity.TextString = "0*0MVA";
            //substCapacity.Label = "变电站容量";
            //substCapacity.InsertionPoint = new gPoint(0, 1.6);
            //blkSubstation.Entities.AddItem(substCapacity);

            //vdXProperty xprop = new vdXProperty();
            //xprop.Name = "变电站名称";
            //xprop.PropValue = "变电站0";
            //blkSubstation.XProperties.AddItem(xprop);
            //xprop = new vdXProperty();
            //xprop.Name = "变电站型号";
            //xprop.PropValue = "型号0";
            //blkSubstation.XProperties.AddItem(xprop);
            //xprop = new vdXProperty();
            //xprop.Name = "输入电压等级";
            //xprop.PropValue = 0;
            //blkSubstation.XProperties.AddItem(xprop);
            //xprop = new vdXProperty();
            //xprop.Name = "输出电压等级";
            //xprop.PropValue = 0;
            //blkSubstation.XProperties.AddItem(xprop);
            //xprop = new vdXProperty();
            //xprop.Name = "主变数量";
            //xprop.PropValue = 0;
            //blkSubstation.XProperties.AddItem(xprop);
            //xprop = new vdXProperty();
            //xprop.Name = "主变容量";
            //xprop.PropValue = 0;
            //blkSubstation.XProperties.AddItem(xprop);
            //xprop = new vdXProperty();
            //xprop.Name = "供电负荷";
            //xprop.PropValue = 0.0;
            //blkSubstation.XProperties.AddItem(xprop);
            //xprop = new vdXProperty();
            //xprop.Name = "出线间隔";
            //xprop.PropValue = 0;
            //blkSubstation.XProperties.AddItem(xprop);

            vdFC.BaseControl.ActiveDocument.Blocks.AddItem(blkSubstation);


            //生成环网单元块
            vdBlock blkLoopstation = new vdBlock();
            blkLoopstation.SetUnRegisterDocument(vdFC.BaseControl.ActiveDocument);
            blkLoopstation.setDocumentDefaults();

            vdPolyline plineH = new vdPolyline();
            plineH.SetUnRegisterDocument(vdFC.BaseControl.ActiveDocument);
            plineH.setDocumentDefaults();
            plineH.VertexList.Add(new gPoint(1, 1));
            plineH.VertexList.Add(new gPoint(1, -1));
            plineH.VertexList.Add(new gPoint(-1, -1));
            plineH.VertexList.Add(new gPoint(-1, 1));
            plineH.VertexList.Add(new gPoint(1, 1));
            blkLoopstation.Entities.AddItem(plineH);

            blkLoopstation.Origin = new gPoint(0, 0);
            blkLoopstation.Name = "MyLoopstationModel";

            vdAttribDef attribdefH = new vdAttribDef();
            attribdefH.SetUnRegisterDocument(vdFC.BaseControl.ActiveDocument);
            attribdefH.setDocumentDefaults();
            attribdefH.InsertionPoint = new gPoint(-0.5, -0.8);
            attribdefH.TagString = "LoopstationS";
            attribdefH.ValueString = "S";
            attribdefH.Bold = true;
            attribdefH.Height = 1.6;
            blkLoopstation.Entities.AddItem(attribdefH);

            vdAttribDef attribdefHName = new vdAttribDef();
            attribdefHName.SetUnRegisterDocument(vdFC.BaseControl.ActiveDocument);
            attribdefHName.setDocumentDefaults();
            attribdefHName.InsertionPoint = new gPoint(-1, 1);
            attribdefHName.TagString = "LoopstationName";
            attribdefHName.ValueString = "环网站1";
            blkLoopstation.Entities.AddItem(attribdefHName);

            vdFC.BaseControl.ActiveDocument.Blocks.AddItem(blkLoopstation);
            
        }

        void BaseControl_vdDoubleClick(EventArgs e, ref bool cancel)
        {
            vdFigure fig;
            MouseEventArgs eL = (MouseEventArgs)e;
            if (eL != null)
            {
                gPoint pt = vdFC.BaseControl.ActiveDocument.CursorPosCCS(eL.Location);
                gPoint p1 = vdFC.BaseControl.ActiveDocument.World2PixelMatrix.Transform(pt as gPoint);
                Point location = new Point((int)p1.x, (int)p1.y);
                fig = vdFC.BaseControl.ActiveDocument.ActiveLayOut.GetEntityFromPoint(location, vdFC.BaseControl.ActiveDocument.ActiveLayOut.Render.GlobalProperties.PickSize, false);
                if (fig == null)
                {
                    vdFC.vdGrid.SelectedObject = vdFC.BaseControl.ActiveDocument;
                    //this.Text = "NO Entity clicked";
                }
                else
                {
                    //vdFC.vdGrid.SelectedObject = fig;

                    //VectorDraw.Professional.Dialogs.frmShowXProperties.Show(vdFC.BaseControl.ActiveDocument, fig.XProperties);
                    if (fig is vdInsert)
                    {
                        vdInsert ins = (vdInsert)fig;
                        for (int i = 0; i < StaticVariables.substationList.Count; i++)
                        {
                            if (ins == StaticVariables.substationList[i].InsSubstation)
                            {
                                StaticVariables.substationIndex = i;
                                break;
                            }
                        }
                        frmSubstation frm = new frmSubstation();
                        frm.ShowDialog();
                    }
                }
            }
        }

        //产生测试数据，仅仅用于测试。
        private void simpleButton1_Click(object sender, EventArgs e)
        {
            
            
            //首先产生环网站数据
            for (int i = 0; i < 100; i++)
            {
                Loopstation loopst = new Loopstation();
                loopst.LoopstID = i + 1;
                loopst.LoopstName = "环网站" + (i + 1).ToString();
                Random ran = new Random();
                loopst.LoopstX = ran.Next(i) % 2000 - 1000;
                loopst.LoopstY = ran.Next(i * i) % 2000 - 1000;
                int landNum = (StaticVariables.landList.Count - 1) < i ? (StaticVariables.landList.Count - 1) : i;
                loopst.LandList.Add(StaticVariables.landList[landNum]);
                loopst.LoopstType = "环网站型号一";
                loopst.VoltageLevel = 10;
                loopst.Load = StaticVariables.landList[landNum].LandLoadM;
                loopst.Capacity = 1000;
                loopst.StandardUnitTID = ran.Next(i * i * i) % 10 + 1;
                loopst.FlagID = 1;
                loopst.ControlNum = i;
                StaticVariables.loopstationList.Add(loopst);
            }

            //产生开关站信息
            for (int i = 100; i < 121; i++)
            {
                SwitchStation switchst = new SwitchStation();
                switchst.SwitchStID = i - 99;
                switchst.SwitchStName = "开关站" + (i - 99).ToString();
                Random ran = new Random();
                switchst.SwitchStX = ran.Next(i * i * i - i * i + 100) % 2000 - 1000;
                switchst.SwitchStY = ran.Next(i * i * i + 7 * i) % 2000 - 1000;
                switchst.SwitchStType = "开关站型号一";
                switchst.VoltageLevel = 10;
                switchst.Load = ran.Next(i * i + 100 - i) % 2000 + 1000;
                switchst.Capacity = 4000;
                switchst.StandardUnitTID = ran.Next(i * i * i) % 10 + 1;
                switchst.FlagID = 1;
                switchst.ControlNum = i;
                StaticVariables.switchStationList.Add(switchst);
            }



            //产生开关站信息
            for (int i = 100; i < 121; i++)
            {
                SwitchStation switchst = new SwitchStation();
                switchst.SwitchStID = i - 99;
                switchst.SwitchStName = "开关站" + (i - 99).ToString();
                Random ran = new Random();
                switchst.SwitchStX = ran.Next(i * i * i - i * i + 100) % 2000 - 1000;
                switchst.SwitchStY = ran.Next(i * i * i + 7 * i) % 2000 - 1000;
                switchst.SwitchStType = "开关站型号一";
                switchst.VoltageLevel = 10;
                switchst.Load = ran.Next(i * i + 100 - i) % 2000 + 1000;
                switchst.Capacity = 4000;
                switchst.StandardUnitTID = ran.Next(i * i * i) % 10 + 1;
                switchst.FlagID = 1;
                switchst.ControlNum = i;
                StaticVariables.switchStationList.Add(switchst);
            }

            //产生变电站信息
            StaticVariables.substationList.Clear();
            for (int i = 121; i < 126; i++)
            {
                Substation subst = new Substation();
                subst.SubstID = i - 120;
                subst.SubstName = "变电站" + (i - 120).ToString();
                subst.SubstType = "变电站型号一";
                Random ran = new Random();
                subst.SubstX = ran.Next(i * i * i - i * i + 100) % 2000 - 1000;
                subst.SubstY = ran.Next(i * i * i + 7 * i) % 2000 - 1000;
                subst.IVoltageLevel = 110;
                subst.OVoltageLevel = 10;
                subst.TransfNum = 2;
                subst.Capacity = 100000;
                subst.Load = ran.Next(i * i * i + 7 * i) % 100000;
                subst.IntervalNum = 10;
                subst.FlagID = 1;
                subst.ControlNum = i;
                StaticVariables.substationList.Add(subst);
            }

            //产生标准单元信息
            //int ID;
            //int standardUnitID;
            //List<Substation> substationList = new List<Substation>();
            //List<SwitchStation> switchstationList = new List<SwitchStation>();
            //List<Loopstation> loopstationList = new List<Loopstation>();
            //List<Land> landList = new List<Land>();
            //List<Transline> translineList = new List<Transline>();
            for (int i = 0; i < 10; i++)
            {
                StandardUnit unit = new StandardUnit();
                unit.SID = i + 1;
                unit.StandardUnitID = i + 1;
                for (int j = 0; j < 2; j++)
                {
                    unit.LoopstationList.Add(StaticVariables.loopstationList[j+i]);
                }
                StaticVariables.standardUnitList.Add(unit);
            }

            //产生输电线信息

            //int startP;
            //int endP;
            //double load;
            //int standardUnitTID;
            //int flagID;
            //int voltageLevel;
            //double capacity;
            for (int i = 126; i <= 405; i++)
            {
                Transline line = new Transline();
                line.TID = i;
                int flag = 0;
                string str = GetLineID(i-125,out flag);
                line.TranslineID = str.ToCharArray();
                Random ran = new Random();
                line.TranslineTypeID = ran.Next(i * i * i) % 3 + 1;
                
                if (line.TranslineTypeID == 1) { line.TranslineType = "YJV22_3_300"; }
                else if (line.TranslineTypeID == 2) { line.TranslineType = "JKLYJ_10_185"; }
                else { line.TranslineType = "VLV22"; }
                line.TranslineLen = ran.Next(i * i * i) % 122354.26;
                if(flag==1)
                    line.StartP = ran.Next(i * i * i + i * i) % 5+121;
                else
                    line.StartP = ran.Next(i * i * i + i * i) % 121;
                line.EndP = ran.Next(i * i * i  - i * i) % 121;
                line.Load = ran.Next (i * i * i  - i * i) % 4000;
                line.StandardUnitID = ran.Next(i * i * i - i * i) % 10+1;
                line.FlagID = 1;
                line.VoltageLevel = 10;
                line.Capacity = 4000;
                StaticVariables.translineList.Add(line);
            }
            MessageBox.Show("产生测试数据成功！");

        }

        public string GetLineID(int i,out int flag)
        {
            flag = 0;
            int standardUnitID = (i-1) / 28 + 1;
            string ID1="";
            if (standardUnitID < 10)
            {
                ID1 = "00" + standardUnitID.ToString();
            }
            else if (standardUnitID < 100)
            {
                ID1 = "0" + standardUnitID.ToString();
            }
            else if (standardUnitID < 1000)
            {
                ID1 = standardUnitID.ToString();
            }
            else { }
            int j = (i-1) % 28 + 1;
            string ID2="";
            if (j < 5)
            {
                flag = 1;
                ID2 = "00" + j.ToString();
            }
            else if (j < 13)
            {
                
                int num = j - 4;//1-8
                int x1 = (num - 1) /2+1;
                int x2 = (num - 1) % 2 + 1;
                ID2 = "0" + x1.ToString() + x2.ToString();
            }
            else if (j < 29)
            {
                int num = j - 12;//1-16
                int x1 = (num-1) / 4 + 1;
                int x2 = ((num - 1) % 4)/2+1;
                int x3 = (num - 1) % 2 + 1;
                ID2 = x1.ToString() + x2.ToString()+x3.ToString();
            }
            string ID = ID1 + ID2;

            return ID;
        }

        private void iLoadRatio_ItemClick(object sender, ItemClickEventArgs e)
        {
            tcgMain.SelectedTabPageIndex = 4;
            tabEvaluation.SelectedTabPageIndex = 3;

            DataTable dtLoadRatio = new DataTable("主干线负载率");
            dtLoadRatio.Columns.Add("loadRatioID", typeof(int));
            dtLoadRatio.Columns.Add("translineIDLR", typeof(string));
            dtLoadRatio.Columns.Add("loadLR", typeof(double));
            dtLoadRatio.Columns.Add("capacityLR", typeof(double));
            dtLoadRatio.Columns.Add("loadRatio", typeof(double));

            int lineNum = 0;
            for (int i = 0; i < StaticVariables.translineList.Count;i++ )
            {
                Transline line = StaticVariables.translineList[i];
                
                if (line.TranslineTypeID == 1) // 只判断主干线
                {
                    dtLoadRatio.Rows.Add(new object[]{lineNum+1, new string(line.TranslineID),line.Load,line.Capacity,line.Load/line.Capacity});
                    lineNum++;
                }
            }
            gcLoadRatio.DataSource = dtLoadRatio;  
        }

        private void gvLoadRatio_CustomDrawCell(object sender, DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventArgs e)
        {
            if (e.Column.FieldName == "loadRatio")
            {
                GridCellInfo GridCellInfo = e.Cell as GridCellInfo;
                if (GridCellInfo.IsDataCell && double.Parse(GridCellInfo.CellValue.ToString()) >=0.7)
                    e.Appearance.BackColor = Color.Red;
            }

        }






        private void iUserManage_ItemClick(object sender, ItemClickEventArgs e)
        {
            tcgMain.SelectedTabPageIndex = 5;
            tabUserManage.SelectedTabPageIndex = 0;
            userGridControl.DataSource = userDataTable;
            btnAddUser.Enabled = true;
            btnUpdateUser.Enabled = true;
            btnDeleteUser.Enabled = true;
            btnAlterUserPwd.Enabled = true;
        }

        private void iOutgoingLine_ItemClick(object sender, ItemClickEventArgs e)
        {
            tcgMain.SelectedTabPageIndex = 4;
            tabEvaluation.SelectedTabPageIndex = 0;

            DataTable dtSubstNumOutgoingLine = new DataTable("变电站出线间隔");
            dtSubstNumOutgoingLine.Columns.Add("substNumOutgoing", typeof(int));
            dtSubstNumOutgoingLine.Columns.Add("substNameOutgoing", typeof(string));
            dtSubstNumOutgoingLine.Columns.Add("intervalNumOutgoing", typeof(int));
            dtSubstNumOutgoingLine.Columns.Add("outgoingLineNum", typeof(int));
            dtSubstNumOutgoingLine.Columns.Add("outgoingLineNumExist", typeof(int));
            
            for (int i = 0; i < StaticVariables.substationList.Count; i++)
            {
                Substation subst = StaticVariables.substationList[i];
                int outgoingLineNum = StaticMethods.GetSubstOutgoingNum(subst,StaticVariables.translineList);
                dtSubstNumOutgoingLine.Rows.Add(new object[] { i + 1, subst.SubstName, subst.IntervalNum, outgoingLineNum, subst.IntervalNum - outgoingLineNum });
            }

            gcOutgoingLine.DataSource = dtSubstNumOutgoingLine;  
        }

        private void iSupplyRadius_ItemClick(object sender, ItemClickEventArgs e)
        {
            tcgMain.SelectedTabPageIndex = 4;
            tabEvaluation.SelectedTabPageIndex = 1;

            DataTable dtSupplyRadius = new DataTable("变电站供电半径");
            dtSupplyRadius.Columns.Add("substIDSR", typeof(int));
            dtSupplyRadius.Columns.Add("substNameSR", typeof(string));
            dtSupplyRadius.Columns.Add("supplyRadius", typeof(double));

            for (int i = 0; i < StaticVariables.substationList.Count; i++)
            {
                Substation subst = StaticVariables.substationList[i];          
                dtSupplyRadius.Rows.Add(new object[] { i + 1, subst.SubstName, subst.GetSupplyRadius(StaticVariables.translineList) });
            }

            gcSupplyRadius.DataSource = dtSupplyRadius;


            DataTable dtSupplyRadiusLine = new DataTable("主干线供电半径");
            dtSupplyRadiusLine.Columns.Add("supplyRadiusID", typeof(int));
            dtSupplyRadiusLine.Columns.Add("translineIDSR", typeof(string));
            dtSupplyRadiusLine.Columns.Add("translineTypeSR", typeof(string));
            dtSupplyRadiusLine.Columns.Add("standardUnitIDSR", typeof(int));
            dtSupplyRadiusLine.Columns.Add("supplyRadiusLine", typeof(double));

            List<Transline> trunkList=new List<Transline>();
            for (int i = 0; i < StaticVariables.translineList.Count; i++)
            {
                char[] translineID = StaticVariables.translineList[i].TranslineID;
                //string s1 = translineID[0].ToString() + translineID[1].ToString() + translineID[2].ToString();
                //int standarUnitID = int.Parse(s1);
                string s2 = translineID[3].ToString() + translineID[4].ToString() + translineID[5].ToString();
                if (s2 == "001" || s2 == "002" || s2 == "003" || s2 == "004")
                    trunkList.Add(StaticVariables.translineList[i]);
            }


            for (int i = 0; i < trunkList.Count; i++)
            {
                Transline line = trunkList[i];
                dtSupplyRadiusLine.Rows.Add(new object[] { i + 1, new string(line.TranslineID), line.TranslineType,line.StandardUnitID,line.GetSupplyRadius(StaticVariables.translineList) });
            }

            gcSupplyRadiusLine.DataSource = dtSupplyRadiusLine; 
        }

        private void barbtnSelectNone_ItemClick(object sender, ItemClickEventArgs e)
        {
            if (vdFC.BaseControl.ActiveDocument.ActiveLayOut.OverAllActiveActions != null && vdFC.BaseControl.ActiveDocument.ActiveLayOut.OverAllActiveActions.Count == 1)
            {
                vdFC.BaseControl.ActiveDocument.CommandAction.Cancel1();
            }
            else { MessageBox.Show("另一命令正在执行！"); }
        }

        private void vdFC_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                MessageBox.Show("触发右击事件！");
                popupMenuVDF.ShowPopup(Control.MousePosition);

            }
        }

        private void vdFC_Load(object sender, EventArgs e)
        {
            vdFC.UnLoadMenu();
            vdFC.SetLayoutStyle(vdControls.vdFramedControl.LayoutStyle.PropertyGrid, false);
            vdDocument doc = vdFC.BaseControl.ActiveDocument;
            doc.FileProperties.ImportDWGFlags = vdFileProperties.DWGImportFlags.IgnoreOnePolylineHatches;
            
        }

        //初始化整个权限管理模块所需的数据
        private void InitAuthManageData()
        {
            userDataTable = OracleDBHelp.GetQueryResult(OracleDBHelp.GetOracleConnection(connectStr, connectUname, connectUpwd),
                "select * from view_user");
            authDataTable = OracleDBHelp.GetQueryResult(OracleDBHelp.GetOracleConnection(connectStr, connectUname, connectUpwd),
                "select * from view_auth");
            menuDataTable = OracleDBHelp.GetQueryResult(OracleDBHelp.GetOracleConnection(connectStr, connectUname, connectUpwd),
                "select * from view_menu");
            tcgMain.SelectedTabPageIndex = 0;
        }



        //初始化菜单项哈希表，并使所有菜单为不可选状态
        private void InitMenuState()
        {
            htMenuItem.Add(iUserSetting.Caption, iUserSetting);
            htMenuItem.Add(iAuthMamage.Caption, iAuthMamage);
            htMenuState.Clear();
            foreach (DataRow dr in menuDataTable.Rows)
            {
                string menuName = dr["MENUNAME"] as string;
                try
                {
                    htMenuState.Add(menuName, false);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                }
            }
        }


        #region
        ///<summary>
        ///用户信息列表界面的按钮事件
        /// </summary>

        //响应点击添加用户按钮产生的事件
        private void btnAddUser_Click(object sender, EventArgs e)
        {
            //初始化用户角色下拉框
            cmbUserAuth.Properties.Items.Clear();
            int rows = authDataTable.Rows.Count;
            for (int i = 0; i < rows; i++)
            {
                string authName = (string)authDataTable.Rows[i]["AUTHNAME"];
                cmbUserAuth.Properties.Items.Add(authName);
            }
            //切换到添加用户页面
            tcgMain.SelectedTabPageIndex = 0;
            tabUserManage.SelectedTabPageIndex = 1;
        }

        //响应点击修改用户按钮产生的事件
        private void btnUpdateUser_Click(object sender, EventArgs e)
        {
            DataRow[] dt = userDataTable.Select("SELECTED='1'");
            if (dt.Length == 0)
            {
                MessageBox.Show("您必须而且只能选择一个用户!");
            }
            else if (dt.Length > 1)
            {
                MessageBox.Show("您只能选择一个用户!");
            }
            else
            {
                //给用户角色下拉框增加数据
                cmbAlterUserAuth.Properties.Items.Clear();
                int rows = authDataTable.Rows.Count;
                for (int i = 0; i < rows; i++)
                {
                    string authName = (string)authDataTable.Rows[i]["AUTHNAME"];
                    cmbAlterUserAuth.Properties.Items.Add(authName);
                }
                //获取当前选中用户的信息，并传递给修改用户界面
                string uid = (string)dt[0]["USERID"];
                string uname = (string)dt[0]["USERNAME"];
                string authname = (string)dt[0]["AUTHNAME"];
                string remark = "";
                try
                {
                    remark = (string)dt[0]["REMARK"];
                }
                catch
                {
                    Console.WriteLine(e);
                }
                txtAlterUserId.Text = uid;
                txtAlterUserName.Text = uname;
                cmbAlterUserAuth.SelectedItem = authname;
                txtAlterUserRemark.Text = remark;
                //设置修改用户标签页选中
                tabUserManage.SelectedTabPageIndex = 2;
            }
        }

        //响应点击删除用户按钮产生的事件
        private void btnDeleteUser_Click(object sender, EventArgs e)
        {
            //判断用户是否选择要删除的用户
            DataRow[] dt = userDataTable.Select("SELECTED='1'");
            if (dt.Length == 0)
            {
                MessageBox.Show("您必须至少选择一个用户!");
            }
            else
            {
                MessageBoxButtons mbtn = MessageBoxButtons.YesNo;
                DialogResult dResult = MessageBox.Show("确定要删除所选的用户吗?", "确认删除用户", mbtn);
                if (dResult == DialogResult.Yes)
                {
                    for (int i = 0; i < dt.Length; i++)
                    {
                        try
                        {
                            //从数据库中删除用户
                            string uid = (string)dt[i]["USERID"];
                            string sql = String.Format("delete from tuser where userid='{0}'", uid);
                            OracleDBHelp.DeleteRecord(OracleDBHelp.GetOracleConnection(connectStr, connectUname, connectUpwd), sql);
                        }
                        catch
                        {
                            Console.WriteLine(e);
                        }
                        //从DataTable中删除用户
                        userDataTable.Rows.Remove(dt[i]);
                    }
                }
            }
        }

        //响应点击修改用户密码按钮产生的事件
        private void btnAlterUserPwd_Click(object sender, EventArgs e)
        {
            DataRow[] dt = userDataTable.Select("SELECTED='1'");
            if (dt.Length == 0)
            {
                MessageBox.Show("您必须而且只能选择一个用户!");
            }
            else if (dt.Length > 1)
            {
                MessageBox.Show("您只能选择一个用户!");
            }
            else
            {
                tabUserManage.SelectedTabPageIndex = 3;
            }
        }

        #endregion


        #region
        ///<summary>
        ///用户管理模块的功能实现
        /// </summary>

        //添加新用户到数据库
        private void btnAddUserOk_Click(object sender, EventArgs e)
        {
            //获取输入的新用户信息
            string uid = this.txtUserId.Text;
            string uname = this.txtUserName.Text;
            string upwd = this.txtUserPwd.Text;
            string authName = this.cmbUserAuth.Text;
            string remark = null;
            if (txtUserRemark.EditValue != null)
                remark = txtUserRemark.Text;
            int authlevel = 3;
            try
            {
                authlevel = int.Parse("" + authDataTable.Select("AUTHNAME='" + authName + "'")[0]["AUTHLEVEL"]);
            }
            catch
            {
                Console.WriteLine(e);
            }
            if (!this.errpInput.HasErrors)
            {
                //将新用户信息插入到数据库中
                string sql = String.Format("insert into tuser(userid,username,password,authlevel,remark) values('{0}','{1}','{2}',{3},'{4}')", uid, uname, upwd, authlevel, remark);
                OracleDBHelp.InsertRecord(OracleDBHelp.GetOracleConnection(connectStr, connectUname, connectUpwd), sql);
                //更新用户信息列表并显示
                userDataTable.Rows.Add(new object[] { '0', uid, uname, upwd, authName, remark });
                tabUserManage.SelectedTabPageIndex = 0;
                ResetAddUser();
            }
            else
            {
                this.errpInput.ContainerControl.Focus();
            }
        }

        //提交修改后的用户信息到数据库
        private void btnAlterUserOk_Click(object sender, EventArgs e)
        {
            //获取修改后的用户信息
            string uid = this.txtAlterUserId.Text;
            string uname = this.txtAlterUserName.Text;
            string authName = this.cmbAlterUserAuth.Text;
            string upwd = null;
            string remark = null;
            if (txtAlterUserPwd.EditValue != null)
                upwd = txtAlterUserPwd.Text;
            if (txtAlterUserRemark.EditValue != null)
                remark = txtAlterUserRemark.Text;
            int authlevel = 3;
            try
            {
                authlevel = int.Parse("" + authDataTable.Select("AUTHNAME='" + authName + "'")[0]["AUTHLEVEL"]);
            }
            catch
            {
                Console.WriteLine(e);
            }
            if (!this.errpInput.HasErrors)
            {
                //将修改后的用户信息更新到数据库中
                string sql = String.Format("update tuser set username='{0}', password='{1}', authlevel='{2}', remark='{3}' where userid='{4}'", uname, upwd, authlevel, remark, uid);
                OracleDBHelp.UpdateRecord(OracleDBHelp.GetOracleConnection(connectStr, connectUname, connectUpwd), sql);
                //更新用户信息列表并显示
                DataRow dr = userDataTable.Select("USERID='" + uid + "'")[0];
                dr.BeginEdit();
                dr["USERNAME"] = uname;
                dr["USERPWD"] = upwd;
                dr["AUTHNAME"] = authName;
                dr["REMARK"] = remark;
                dr.EndEdit();
                tabUserManage.SelectedTabPageIndex = 0;
                ResetAlterUser();
            }
            else
            {
                this.errpInput.ContainerControl.Focus();
            }
        }

        //提交修改后的用户密码到数据库
        private void btnAlterPwdOk_Click(object sender, EventArgs e)
        {
            //若输入的数据通过验证，则将新密码提交到数据库
            if (!this.errpInput.HasErrors)
            {
                string newPwd = this.txtNewPwd.Text;
                DataRow dr = userDataTable.Select("SELECTED='1'")[0];
                string uid = (string)dr["USERID"];
                string sql = String.Format("update tuser set password='{0}' where userid ='{1}'", newPwd, uid);
                OracleDBHelp.UpdateRecord(OracleDBHelp.GetOracleConnection(connectStr, connectUname, connectUpwd), sql);
                dr.BeginEdit();
                dr["USERPWD"] = newPwd;
                dr.EndEdit();
                tabUserManage.SelectedTabPageIndex = 0;
                ResetAlterPwd();
            }
            else
            {
                this.errpInput.ContainerControl.Focus();
            }
        }

        //验证用户修改密码时输入的当前密码是否正确
        private void txtOldPwd_Validating(object sender, CancelEventArgs e)
        {
            string oldPwd = this.txtOldPwd.Text;
            DataRow dr = userDataTable.Select("SELECTED='1'")[0];
            if (!dr["USERPWD"].Equals(oldPwd))
            {
                //e.Cancel = true;
                this.txtOldPwd.SelectAll();
                this.errpInput.SetError(txtOldPwd, "当前密码不正确，请重新输入!");
                this.errpInput.SetIconAlignment(txtOldPwd, ErrorIconAlignment.MiddleRight);
            }
            else
            {
                //e.Cancel = false;
                this.errpInput.ClearErrors();
            }
        }

        //修改密码时验证用户两次输入的密码是否相同
        private void txtConfirmNewPwd_Validating(object sender, CancelEventArgs e)
        {
            string newPwd = txtNewPwd.Text;
            string confirmNewPwd = txtConfirmNewPwd.Text;
            if (!confirmNewPwd.Equals(newPwd))
            {
                //e.Cancel = false;
                this.txtConfirmNewPwd.SelectAll();
                this.errpInput.SetError(txtConfirmNewPwd, "与前面输入的密码不一致，请重新输入!");
                this.errpInput.SetIconAlignment(txtConfirmNewPwd, ErrorIconAlignment.MiddleRight);
            }
            else
            {
                //e.Cancel = false;
                this.errpInput.ClearErrors();
            }
        }

        //添加用户时验证用户两次输入的密码是否相同
        private void txtConfirmPwd_Validating(object sender, CancelEventArgs e)
        {
            string upwd = txtUserPwd.Text;
            string confirmUpwd = txtConfirmPwd.Text;
            if (!confirmUpwd.Equals(upwd))
            {
                //e.Cancel = false;
                this.txtConfirmPwd.SelectAll();
                this.errpInput.SetError(txtConfirmPwd, "与前面输入的密码不一致，请重新输入!");
                this.errpInput.SetIconAlignment(txtConfirmPwd, ErrorIconAlignment.MiddleRight);
            }
            else
            {
                //e.Cancel = false;
                this.errpInput.ClearErrors();
            }
        }

        //修改用户时验证用户两次输入的密码是否相同
        private void txtConfirmAlterPwd_Validating(object sender, CancelEventArgs e)
        {
            string upwd = txtAlterUserPwd.Text;
            string confirmUpwd = txtConfirmAlterPwd.Text;
            if (!confirmUpwd.Equals(upwd))
            {
                //e.Cancel = false;
                this.txtConfirmAlterPwd.SelectAll();
                this.errpInput.SetError(txtConfirmAlterPwd, "与前面输入的密码不一致，请重新输入!");
                this.errpInput.SetIconAlignment(txtConfirmAlterPwd, ErrorIconAlignment.MiddleRight);
            }
            else
            {
                //e.Cancel = false;
                this.errpInput.ClearErrors();
            }
        }

        //取消添加用户，返回到用户信息显示界面
        private void btnCancelAddUser_Click(object sender, EventArgs e)
        {
            ResetAddUser();
            tabUserManage.SelectedTabPageIndex = 0;
        }

        //放弃修改用户，返回到用户信息显示界面
        private void btnCancelAlterUser_Click(object sender, EventArgs e)
        {
            ResetAlterUser();
            tabUserManage.SelectedTabPageIndex = 0;
        }

        //放弃修改用户密码，返回到用户信息显示界面
        private void btnCancelAlterPwd_Click(object sender, EventArgs e)
        {
            ResetAlterPwd();
            tabUserManage.SelectedTabPageIndex = 0;
        }

        //重置添加用户的信息输入框
        private void ResetAddUser()
        {
            this.txtUserId.Text = "";
            this.txtUserName.Text = "";
            this.txtUserRemark.Text = "";
            cmbUserAuth.SelectedItem = "";
        }

        //重置修改用户的信息输入框
        private void ResetAlterUser()
        {
            this.txtAlterUserId.Text = "";
            this.txtAlterUserName.Text = "";
            this.txtAlterUserPwd.Text = "";
            this.txtConfirmAlterPwd.Text = "";
            this.txtAlterUserRemark.Text = "";
            this.cmbAlterUserAuth.SelectedItem = "";
        }

        //重置修改密码的信息输入框
        private void ResetAlterPwd()
        {
            this.txtOldPwd.Text = "";
            this.txtNewPwd.Text = "";
            this.txtConfirmNewPwd.Text = "";
        }

        #endregion

        #region
        ///<summary>
        ///权限列表界面的按钮事件
        /// </summary>

        //响应添加权限按钮的点击事件
        private void btnAddAuth_Click(object sender, EventArgs e)
        {
            tcgMain.SelectedTabPageIndex = 1;
            tabAuthManage.SelectedTabPageIndex = 1;
        }

        //响应修改权限按钮的点击事件
        private void btnAlterAuth_Click(object sender, EventArgs e)
        {

        }

        //响应删除权限按钮事件
        private void btnDeleteAuth_Click(object sender, EventArgs e)
        {

        }

        //响应用户授权按钮的点击事件
        private void btnAuthToUser_Click(object sender, EventArgs e)
        {

        }

        //响应菜单授权按钮的点击事件
        private void btnAuthToMenu_Click(object sender, EventArgs e)
        {

        }

        #endregion

        #region
        ///<summary>
        ///权限管理模块的功能实现
        /// </summary>

        //修改权限信息
        private void btnAlterAuthOk_Click(object sender, EventArgs e)
        {
            //获取修改后的权限信息
            int authlevel = int.Parse(txtAlterAuthlevel.Text);
            string authName = this.txtAlterAuthName.Text;
            string remark = txtAlterAuthRemark.Text;
            //将修改后的权限信息更新到数据库中
            string sql = String.Format("update tauthority set authname='{0}', remark='{1}' where authlevel={2}", authName, remark, authlevel);
            OracleDBHelp.UpdateRecord(OracleDBHelp.GetOracleConnection(connectStr, connectUname, connectUpwd), sql);
            //更新权限信息列表并显示
            DataRow dr = authDataTable.Select("AUTHLEVEL=" + authlevel + "")[0];
            dr.BeginEdit();
            dr["AUTHNAME"] = authName;
            dr["REMARK"] = remark;
            dr.EndEdit();
            //返回到权限信息显示界面
            ResetAlterAuth();
            tabAuthManage.SelectedTabPageIndex = 0;
        }

        //取消修改权限
        private void btnCancelAlterAuth_Click(object sender, EventArgs e)
        {
            ResetAlterAuth();
            tabAuthManage.SelectedTabPageIndex = 0;
        }

        private void ResetAlterAuth()
        {
            txtAlterAuthlevel.Text = "";
            txtAlterAuthName.Text = "";
            txtAlterAuthRemark.Text = "";
        }

        //选择要授予当前权限的用户
        private void btnShiftSelectedToRight_Click(object sender, EventArgs e)
        {

        }

        //将所有未授权用户移到待授权用户列表中
        private void btnShiftAllToRight_Click(object sender, EventArgs e)
        {

        }

        //选择取消授予当前权限的用户
        private void btnShiftSelectedToLeft_Click(object sender, EventArgs e)
        {

        }

        //将所有待授权的用户移到未授予当前权限用户列表
        private void btnShiftAllToLeft_Click(object sender, EventArgs e)
        {

        }

        //给选择的用户授予当前权限
        private void btnAuthUserOk_Click(object sender, EventArgs e)
        {

        }

        //取消授予当前权限，返回到权限主界面
        private void btnCancelAuthUser_Click(object sender, EventArgs e)
        {
            lblCurAuth.Text = "";
            lbcUserList.Items.Clear();
            lbcAuthUser.Items.Clear();
            tabAuthManage.SelectedTabPageIndex = 0;
        }

        //给选择的菜单授予当前权限
        private void btnAuthMenuOk_Click(object sender, EventArgs e)
        {

        }

        //取消给菜单授予当前权限
        private void btnCancelAuthMenu_Click(object sender, EventArgs e)
        {
            //清空菜单授权界面，并跳转到权限主界面
            lblCurAuth_Menu.Text = "";
            tlistMenu.DataSource = null;
            gcAuthMenu.DataSource = null;
            tabAuthManage.SelectedTabPageIndex = 0;
        }

        #region
        ///<summary>
        ///菜单授权辅助功能函数
        /// </summary>

        //节点选择事件
        private void tlistMenu_AfterCheckNode(object sender, DevExpress.XtraTreeList.NodeEventArgs e)
        {
            //设置与该节点相关的节点状态
            SetCheckedChildNodes(e.Node, e.Node.CheckState);
            SetCheckedParentNodes(e.Node, e.Node.CheckState);
            //将选择的节点添加到待授权菜单信息表中
            selectedMenuDataTable = getSelectedMenu(tlistMenu);
            gcAuthMenu.DataSource = selectedMenuDataTable;
        }

        /// <summary>
        /// 选择某一节点时,该节点的子节点全部选择
        /// 取消某一节点时,该节点的子节点全部取消选择
        /// </summary>
        /// <param name="node">节点</param>
        /// <param name="check">节点的选择状态</param>
        private void SetCheckedChildNodes(TreeListNode node, CheckState check)
        {
            for (int i = 0; i < node.Nodes.Count; i++)
            {
                node.Nodes[i].CheckState = check;
                SetCheckedChildNodes(node.Nodes[i], check);
            }
        }

        /// <summary>
        /// 某节点的子节点全部选择时,该节点选择
        /// 某节点的子节点未全部选择时,该节点不选择
        /// </summary>
        /// <param name="node">节点</param>
        /// <param name="check">节点的选择状态</param>
        private void SetCheckedParentNodes(TreeListNode node, CheckState check)
        {
            if (node.ParentNode != null)
            {
                CheckState parentCheckState = node.ParentNode.CheckState;
                CheckState nodeCheckState;
                for (int i = 0; i < node.ParentNode.Nodes.Count; i++)
                {
                    nodeCheckState = (CheckState)node.ParentNode.Nodes[i].CheckState;
                    if (!check.Equals(nodeCheckState))//只要任意一个与其选中状态不一样即父节点状态不全选
                    {
                        parentCheckState = CheckState.Indeterminate;
                        break;
                    }
                    parentCheckState = check;//否则（该节点的兄弟节点选中状态都相同），则父节点选中状态为该节点的选中状态
                }
                node.ParentNode.CheckState = parentCheckState;
                SetCheckedParentNodes(node.ParentNode, check);//遍历上级节点
            }
        }

        //存放选择状态菜单ID的集合
        private List<string> tlMenuID = new List<string>();

        /// <summary>
        /// 获取选择状态的菜单ID集合
        /// </summary>
        /// <param name="parentNode">父级节点</param>
        private void GetCheckedMenuID(TreeListNode parentNode)
        {
            if (parentNode.Nodes.Count == 0)
            {
                return;//递归终止
            }

            foreach (TreeListNode node in parentNode.Nodes)
            {
                if (node.CheckState == CheckState.Checked)
                {
                    DataRowView drv = tlistMenu.GetDataRecordByNode(node) as DataRowView;
                    if (drv != null)
                    {
                        string MenuID = drv["MenuID"] as string;
                        tlMenuID.Add(MenuID);
                    }
                }
                GetCheckedMenuID(node);
            }
        }

        //获得当前选择菜单的信息
        private DataTable getSelectedMenu(TreeList treelist)
        {
            //存放选择状态菜单的DataTable
            DataTable dtSelectedMenu = new DataTable();
            dtSelectedMenu.Columns.Add("ID", typeof(int));
            dtSelectedMenu.Columns.Add("MENUID", typeof(string));
            dtSelectedMenu.Columns.Add("MENUNAME", typeof(string));
            dtSelectedMenu.Columns.Add("REMARK", typeof(string));

            //清空存放MenuID的集合
            this.tlMenuID.Clear();
            //如果菜单有内容，则取出处于选择状态的节点内容放到集合中
            if (treelist.Nodes.Count > 0)
            {
                foreach (TreeListNode root in treelist.Nodes)
                {
                    GetCheckedMenuID(root);
                }
            }
            //将集合中的菜单项取出，放到DataTable中以实现展示
            foreach (string menuID in tlMenuID)
            {
                DataRow[] dr = menuDataTable.Select("MENUID='" + menuID + "'");
                int id = int.Parse("" + dr[0]["ID"]);
                string menuName = dr[0]["MENUNAME"] as string;
                string remark = dr[0]["REMARK"] as string;
                dtSelectedMenu.Rows.Add(new object[] { id, menuID, menuName, remark });
            }
            return dtSelectedMenu;
        }

        /// <summary>
        /// 随着分割条的移动，tlistMenu的宽度也随之改变
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void sccAuthMenu_SplitterPositionChanged(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// 自动显示待授权菜单列表行号
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void gvAuthMenu_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
        {

        }

        #endregion

        #endregion

        //测试权限菜单
        private void testAuthMenu(string uname)
        {
            string filterSql = String.Format("select menuname from view_authmenu where uname = '{0}'", uname);
            DataTable dt = OracleDBHelp.GetQueryResult(OracleDBHelp.GetOracleConnection(connectStr, connectUname, connectUpwd), filterSql);
            foreach (DataRow dr in dt.Rows)
            {
                string menuName = dr["MENUNAME"] as string;
                if (htMenuState.Contains(menuName))
                {
                    htMenuState.Remove(menuName);
                    try
                    {
                        htMenuState.Add(menuName, true);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e);
                    }
                }
            }
            //遍历菜单状态哈希表，设置菜单项的状态
            foreach (DictionaryEntry dems in htMenuState)
            {
                foreach (DictionaryEntry demi in htMenuItem)
                {
                    if (demi.Key.Equals(dems.Key))
                    {
                        BarButtonItem btn = demi.Value as BarButtonItem;
                        btn.Enabled = (bool)dems.Value;
                    }
                }
            }
        }

        private void iAuthMamage_ItemClick(object sender, ItemClickEventArgs e)
        {
            tcgMain.SelectedTabPageIndex = 6;
            tabUserManage.SelectedTabPageIndex = 0;
            authGridControl.DataSource = authDataTable;
            btnAlterAuth.Enabled = true;
            btnAuthToUser.Enabled = true;
            btnAuthToMenu.Enabled = true;
        }

        private void iExcel_ItemClick(object sender, ItemClickEventArgs e)
        {
            ExcelFiles excelFile = new ExcelFiles();
            excelFile.CreateNewExcel();

            Object Nothing = Missing.Value;
            //建立Excel对象 
            Microsoft.Office.Interop.Excel.Application excel = excelFile.ExcelApp;
            Microsoft.Office.Interop.Excel.Workbook workbook = excelFile.ExcelDoc;
            excel.Visible = true;


            for (int i = 0; i < StaticVariables.excelDS.Tables.Count; i++)
            {
                DataTable dataTable = StaticVariables.excelDS.Tables[i];
                int rowNumber = dataTable.Rows.Count;//不包括字段名
                int columnNumber = dataTable.Columns.Count;
                int colIndex = 0;
                if (i > 2)
                {
                    //Microsoft.Office.Interop.Excel.Worksheet ws = new Microsoft.Office.Interop.Excel.Worksheet();
                    workbook.Worksheets.Add(Nothing, (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[i], 1, Nothing);
                   
                    
                }
                Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[i + 1];
                //Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)excel.Worksheets[1];
                Microsoft.Office.Interop.Excel.Range range;

                //生成字段名称 
                foreach (DataColumn col in dataTable.Columns)
                {
                    colIndex++;
                    worksheet.Cells[1, colIndex] = col.ColumnName;
                }

                object[,] objData = new object[rowNumber, columnNumber];

                for (int r = 0; r < rowNumber; r++)
                {
                    for (int c = 0; c < columnNumber; c++)
                    {
                        objData[r, c] = dataTable.Rows[r][c];
                    }
                    //Application.DoEvents();
                }

                if (worksheet != null)
                {
                    range = worksheet.get_Range(worksheet.Cells[2, 1] as Microsoft.Office.Interop.Excel.Range, worksheet.Cells[rowNumber + 1, columnNumber] as Microsoft.Office.Interop.Excel.Range);//需要加上 as Excel.Range   
                    //range.ColumnWidth = width;
                    range.Value2 = objData;
                }
            }

            SaveFileDialog saveDia = new SaveFileDialog();
            saveDia.DefaultExt = "xls";//默认拓展名
            saveDia.Filter = "Excel2003文件 (*.xls)|*.xls|Excel2007文件 (*.xlsx)|*.xlsx";//文件过滤器
            DialogResult dialogResult = saveDia.ShowDialog();
            if (dialogResult == DialogResult.Cancel) return;
            string fileName = saveDia.FileName;

            excelFile.SaveExcelFile(fileName);//@"D:\MyExcel.xlsx"

        }
        /// <summary>
        /// 水晶报表
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void iCR_ItemClick(object sender, ItemClickEventArgs e)
        {
            DataSet ds = StaticVariables.excelDS;
            //ReportDocument doc = new ReportDocument();
            //string rptname = Application.StartupPath + @"\CRTransline.rpt";
            
            //string rptname = @"E:\VS2010 Projects\PDNPAS\PDNPAS\CRTransline.rpt"; // 设计的报表
            //doc.Load(rptname);

            CRTransline doc = new CRTransline();
            doc.SetDataSource(ds.Tables[0]); // 设置数据源
            this.crviewTransline.ReportSource = doc;  // 加载报表

            //ReportDocument doc1 = new ReportDocument();
            //string rptname1 = Application.StartupPath + @"\CRLoopst.rpt";
            ////string rptname1 = @"E:\VS2010 Projects\PDNPAS\PDNPAS\CRLoopst.rpt"; // 设计的报表
            //doc1.Load(rptname1);
            CRLoopst doc1 = new CRLoopst();
            doc1.SetDataSource(ds.Tables[1]); // 设置数据源
            this.crviewLoopst.ReportSource = doc1;  // 加载报表

            //ReportDocument doc2 = new ReportDocument();
            //string rptname2 = Application.StartupPath + @"\CRSwitchst.rpt";
            ////string rptname2 = @"E:\VS2010 Projects\PDNPAS\PDNPAS\CRSwitchst.rpt"; // 设计的报表
            //doc2.Load(rptname2);
            CRSwitchst doc2 = new CRSwitchst();
            doc2.SetDataSource(ds.Tables[2]); // 设置数据源
            this.crviewSwitchst.ReportSource = doc2;  // 加载报表
            
            //ReportDocument doc3 = new ReportDocument();
            //string rptname3 = Application.StartupPath + @"\CRSubst.rpt";
            ////string rptname3 = @"E:\VS2010 Projects\PDNPAS\PDNPAS\CRSubst.rpt"; // 设计的报表
            //doc3.Load(rptname3);
            CRSubst doc3 = new CRSubst();
            doc3.SetDataSource(ds.Tables[3]); // 设置数据源
            this.crviewSubst.ReportSource = doc3;  // 加载报表
            
            //ReportDocument doc4 = new ReportDocument();
            //string rptname4 = Application.StartupPath + @"\CRStandardUnit.rpt";
            ////string rptname4 = @"E:\VS2010 Projects\PDNPAS\PDNPAS\CRStandardUnit.rpt"; // 设计的报表
            //doc4.Load(rptname4);
            CRStandardUnit doc4 = new CRStandardUnit();
            doc4.SetDataSource(ds.Tables[4]); // 设置数据源
            this.crviewStandardunit.ReportSource = doc4;  // 加载报表

        }

        private void iLoadStatistics_ItemClick(object sender, ItemClickEventArgs e)
        {
            tcgMain.SelectedTabPageIndex = 2;
            tabLoadForecast.SelectedTabPageIndex = 1;

            //将相同性质的地块合并，生成新的合并地块列表
            StaticVariables.landCollectionForecastList.Clear();
            double loadTotal = 0;
            for (int i = 0; i < StaticVariables.landList.Count; i++)
            {
                int flag = 0;//表示不包含相同性质的地块
                int index = -1;//存放相同性质地块的index值
                for (int j = 0; j < StaticVariables.landCollectionForecastList.Count; j++)
                {
                    if (StaticVariables.landCollectionForecastList[j].LandPropID == StaticVariables.landList[i].LandPropID)
                    {
                        flag = 1; index = j; break;
                    }
                }
                if (flag == 1)
                {
                    StaticVariables.landCollectionForecastList[index].LandArea += StaticVariables.landList[i].LandArea*StaticVariables.landList[i].AreaCheckCoef;
                    StaticVariables.landCollectionForecastList[index].LandLoadH += StaticVariables.landList[i].LandLoadH*StaticVariables.landList[i].AreaCheckCoef;
                    StaticVariables.landCollectionForecastList[index].LandLoadL += StaticVariables.landList[i].LandLoadL*StaticVariables.landList[i].AreaCheckCoef;
                    StaticVariables.landCollectionForecastList[index].LandLoadM += StaticVariables.landList[i].LandLoadM*StaticVariables.landList[i].AreaCheckCoef;
                    loadTotal += StaticVariables.landList[i].LandLoadM * StaticVariables.landList[i].AreaCheckCoef;
                }
                else
                {
                    StaticVariables.landCollectionForecastList.Add(StaticVariables.landList[i].myClone());
                    loadTotal += StaticVariables.landList[i].LandLoadM * StaticVariables.landList[i].AreaCheckCoef;
                }
            }

            //MessageBox.Show("用地性质类型有：" + StaticVariables.landCollectionForecastList.Count.ToString());

            //在grid control 中显示
            DataTable dt = new DataTable("负荷预测表");
            dt.Columns.Add("landProp", typeof(string));
            dt.Columns.Add("landArea", typeof(double));
            dt.Columns.Add("plotRatio", typeof(double));
            dt.Columns.Add("floorArea", typeof(double));
            dt.Columns.Add("loadDensityH", typeof(double));
            dt.Columns.Add("loadDensityL", typeof(double));
            dt.Columns.Add("landLoadH", typeof(double));
            dt.Columns.Add("landLoadL", typeof(double));
            dt.Columns.Add("simultaneity", typeof(double));
            dt.Columns.Add("landLoad", typeof(double));
     
            for (int i = 0; i < StaticVariables.landCollectionForecastList.Count; i++)
            {
                Land land = new Land();
                land = StaticVariables.landCollectionForecastList[i];
                dt.Rows.Add(new object[] { land.LandProp, land.LandArea, land.PlotRatio, land.LandArea * land.PlotRatio, land.LoadDensityH, land.LoadDensityL, land.LandLoadH, land.LandLoadL, land.Simultaneity, land.LandLoadM });
                
            }

            gcLoadForecastDensity.DataSource = dt;
            double secSimultaneity=0.8;
            txtLoadTotal.Text = (loadTotal * secSimultaneity / 1000000.0).ToString("0.00");
        }

        private void btnLandAreaCheck_Click(object sender, EventArgs e)
        {
            for (int i = 0; i <StaticVariables.landList.Count; i++)
            {
                for (int j = 0; j < dtLandArea.Rows.Count; j++)
                {
                    if (StaticVariables.landList[i].LandProp == dtLandArea.Rows[j]["landProp"].ToString())//
                    {
                        StaticVariables.landList[i].AreaCheckCoef = double.Parse( dtLandArea.Rows[j]["landAreaCheckA"].ToString()) / double.Parse( dtLandArea.Rows[j]["landArea"].ToString());
                    }
                }
            }
            MessageBox.Show("地块面积校正完成。");
        }

        private void iSupplyDivision_ItemClick(object sender, ItemClickEventArgs e)
        {
            //首先判断是否有L供区大范围图层，有的话，新建一个L供区划分图层，并将该图层设置为活动图层，进行标记

            vdLayer layerSupplyBoundary = vdFC.BaseControl.ActiveDocument.Layers.FindName("L供区大范围");
            if (layerSupplyBoundary == null)
            {
                MessageBox.Show("没有找到图层“L供区大范围”，请将CAD文件经过人工协助后再进行辅助规划。");
                return;
            }

            tcgMain.SelectedTabPageIndex = 0;


            vdLayer layerSupply = vdFC.BaseControl.ActiveDocument.Layers.FindName("L供区划分");
            if (layerSupply == null)
            {
                vdLayer newlayer = vdFC.BaseControl.ActiveDocument.Layers.Add("L供区划分");
                newlayer.SetUnRegisterDocument(vdFC.BaseControl.ActiveDocument);
                newlayer.setDocumentDefaults();
                layerSupply = newlayer;
            }
            vdFC.BaseControl.ActiveDocument.ActiveLayer = layerSupply;

            //冻结地块编号图层
            vdLayer tempLayer = vdFC.BaseControl.ActiveDocument.Layers.FindName("L地块编号");
            tempLayer.Frozen = true;

            //扫描L供区大范围内的polyline
            List<vdPolyline> BoundaryLineList = new List<vdPolyline>();
            for (int i = 0; i < vdFC.BaseControl.ActiveDocument.ActiveLayOut.Entities.Count; i++)
            {
                if (vdFC.BaseControl.ActiveDocument.ActiveLayOut.Entities[i] is vdPolyline)
                {
                    vdPolyline pline = (vdPolyline)vdFC.BaseControl.ActiveDocument.ActiveLayOut.Entities[i];
                    if (pline != null && pline.Layer == layerSupplyBoundary)
                    {
                        BoundaryLineList.Add(pline);
                    }
                }
            }
            MessageBox.Show("扫描到的供区大范围多段线的数目为：" + BoundaryLineList.Count);

            //将大负荷地块标记为双环网规划，小负荷地块标记为三双规划，并将大地块统计出来。
            List<Land> landThreeList = new List<Land>();//三双规划地块
            List<Land> landDoubleList = new List<Land>();//双环网规划地块
            for (int i = 0; i < StaticVariables.landList.Count; i++)
            {
                Land land=StaticVariables.landList[i];
                if (land.LandLoadM <= 2000000 && land.LoadDensityH>5.0 )
                {
                    landThreeList.Add(land);
                }
                else if(land.LandLoadM>2000000 && land.LoadDensityH>5.0)
                {
                    landDoubleList.Add(land);
                }
            }
            MessageBox.Show("需要三双供电的地块数目为：" + landThreeList.Count);
            MessageBox.Show("需要双环网供电的地块数目为：" + landDoubleList.Count);

            for (int i = 0; i < BoundaryLineList.Count; i++)
            {
                List<Land> landThreeListTemp = new List<Land>();
                List<Land> landDoubleListTemp = new List<Land>();
                vdPolyline poly = BoundaryLineList[i];
                //Create A Region From the Polyline's points
                VectorDraw.Render.Region reg = new VectorDraw.Render.Region(poly.GetSamplePoints(0, 0));
                //Check if a point is inside the polyline or not.
                for (int j = 0; j < landThreeList.Count; j++) 
                {
                    if(reg.IsPointInside(StaticMethods.GetHatchCentroid(landThreeList[j].Myhatch.Hatch)))
                    {
                        landThreeListTemp.Add(landThreeList[j]);
                    }                    
                }
                for (int j = 0; j < landDoubleList.Count; j++)
                {
                    if (reg.IsPointInside(StaticMethods.GetHatchCentroid(landDoubleList[j].Myhatch.Hatch)))
                    {
                        landDoubleListTemp.Add(landDoubleList[j]);
                    }
                }
                //一个多段线内的三双规划地块进行供区划分
                //地块已经从上到下从左到右排序过
                while (landThreeListTemp.Count > 0)
                {
                    SupplyArea supplyArea = new SupplyArea();
                    if (landThreeListTemp.Count == 1)
                    {
                        supplyArea.LandList.Add(landThreeListTemp[0]);
                        landThreeListTemp.RemoveAt(0);
                        StaticVariables.supplyAreaList.Add(supplyArea);
                        break;
                    }

                    if (landThreeListTemp[0].LandLoadM >750000)//0.75MW
                    {
                        supplyArea.LandList.Add(landThreeListTemp[0]);
                        supplyArea.LoopstationList.Add(new Loopstation());
                        landThreeListTemp.RemoveAt(0);
                        StaticVariables.supplyAreaList.Add(supplyArea);
                    }
                    //合并操作如果负荷小于0.75MW时，
                    //不断与最近的一个地块合并，
                    //直到新的地块负荷大于0.75MW或没有可以合并的地块为止，
                    //当新的地块负荷在0.75~1.5MW时用一个环网单元供电，当新的地块负荷在1.5~2.75MW时用两个环网单元供电。
                    else
                    {
                        List<Land> newLandList = new List<Land>();
                        newLandList.Add(landThreeListTemp[0]);
                        landThreeListTemp.RemoveAt(0);

                        while (landThreeListTemp.Count > 0 && StaticMethods.getTotalLoad(newLandList)<750000) 
                        {
                            Land land = StaticMethods.getClosestLand(landThreeListTemp, newLandList);
                            newLandList.Add(land);
                            landThreeListTemp.Remove(land);
                        }
                        supplyArea.LandList = newLandList;
                        StaticVariables.supplyAreaList.Add(supplyArea);
                    }
                }

                //对于划分好的供区在L供区划分图层进行标记
                for (int m = 0; m < StaticVariables.supplyAreaList.Count; m++)
                {
                    SupplyArea supplyArea = StaticVariables.supplyAreaList[m];
                    if (supplyArea.LandList.Count == 1)
                    {
                        vdMText oneMtext = new vdMText();
                        oneMtext.SetUnRegisterDocument(vdFC.BaseControl.ActiveDocument);
                        oneMtext.setDocumentDefaults(); 
                        oneMtext.InsertionPoint = StaticMethods.GetHatchCentroid(supplyArea.LandList[0].Myhatch.Hatch);
                        oneMtext.HorJustify = VectorDraw.Professional.Constants.VdConstHorJust.VdTextHorCenter; 
                        oneMtext.Height = 16;
                        oneMtext.PenWidth = 3.0;
                        oneMtext.PenColor.SystemColor = Color.Blue;
                        //The Text string can contain some special control characters like "\P" or "\C1" which
                        // control the way that this multiLine text is going to be displayed.
                        oneMtext.TextString = "S"; //StaticVariables.landList[i].LandID + @"\P" + StaticVariables.landList[i].LandProp;//+ @"\P" +StaticVariables.landList[i].LandArea.ToString("0.0");
                        vdFC.BaseControl.ActiveDocument.ActiveLayOut.Entities.AddItem(oneMtext);
                        
                    }
                    else if (supplyArea.LandList.Count == 2)
                    {
                        vdLine line = new vdLine(StaticMethods.GetHatchCentroid(supplyArea.LandList[0].Myhatch.Hatch), StaticMethods.GetHatchCentroid(supplyArea.LandList[1].Myhatch.Hatch));
                        line.SetUnRegisterDocument(vdFC.BaseControl.ActiveDocument);
                        line.setDocumentDefaults();
                        line.PenColor.SystemColor = Color.Blue;
                        line.PenWidth = 3.0;
                        vdFC.BaseControl.ActiveDocument.ActiveLayOut.Entities.AddItem(line);
                        //string lineHandle = line.Handle.ToStringValue();//便于交互
                        string str1 = "L供区划分-合并的两个地块！";
                        line.ToolTip = str1;//设置线条的信息
                    }
                    else if (supplyArea.LandList.Count > 2)
                    {
                        vdPolyline pline = new vdPolyline();
                        for (int n = 0; n < supplyArea.LandList.Count; n++)
                        {
                            pline.VertexList.Add(StaticMethods.GetHatchCentroid(supplyArea.LandList[n].Myhatch.Hatch));
                        }
                        pline.SetUnRegisterDocument(vdFC.BaseControl.ActiveDocument);
                        pline.setDocumentDefaults();
                        pline.PenColor.SystemColor = Color.Blue;
                        pline.PenWidth = 3.0;
                        vdFC.BaseControl.ActiveDocument.ActiveLayOut.Entities.AddItem(pline);
                        //string lineHandle = line.Handle.ToStringValue();//便于交互
                        string str1 = "L供区划分-合并的" + supplyArea.LandList.Count + "个地块！";
                        pline.ToolTip = str1;//设置线条的信息
                        
                    }

                }


                //一个多段线内的双环网规划地块进行供区划分
                //!!!!!!!!!!!!!!!!!!!!!!双环网规划！！！！！！！！！！！！！
            }
            //目前只进行标记
            for (int m = 0; m < landDoubleList.Count; m++)
            {
                vdMText oneMtext = new vdMText();
                oneMtext.SetUnRegisterDocument(vdFC.BaseControl.ActiveDocument);
                oneMtext.setDocumentDefaults();
                oneMtext.InsertionPoint = StaticMethods.GetHatchCentroid(landDoubleList[m].Myhatch.Hatch);
                oneMtext.HorJustify = VectorDraw.Professional.Constants.VdConstHorJust.VdTextHorCenter;
                oneMtext.Height = 16;
                oneMtext.PenWidth = 3.0;
                oneMtext.PenColor.SystemColor = Color.SeaGreen;//海绿色
                //The Text string can contain some special control characters like "\P" or "\C1" which
                // control the way that this multiLine text is going to be displayed.
                oneMtext.TextString = "H"; //StaticVariables.landList[i].LandID + @"\P" + StaticVariables.landList[i].LandProp;//+ @"\P" +StaticVariables.landList[i].LandArea.ToString("0.0");
                vdFC.BaseControl.ActiveDocument.ActiveLayOut.Entities.AddItem(oneMtext);

            }
             
            vdFC.BaseControl.ActiveDocument.Redraw(true);
        }

        private void iLoopstLocation_ItemClick(object sender, ItemClickEventArgs e)
        {
            if (vdFC.BaseControl.ActiveDocument.Blocks.FindName("MyLoopstationModel") == null)
            {
                MessageBox.Show("环网单元模型未定义！");
                return;
            }

            tcgMain.SelectedTabPageIndex = 0;

            for (int i = 0; i < StaticVariables.supplyAreaList.Count; i++)
            {
                double totalLoad = StaticMethods.getTotalLoad(StaticVariables.supplyAreaList[i].LandList);
                int loopstNum = StaticMethods.getLoopstNum(totalLoad);
                StaticVariables.supplyAreaList[i].LoopstationList.Clear();
                if (loopstNum == 1)
                {
                    double sumOfXP = 0;
                    double sumOfYP = 0;
                    double sumOfP = 0;
                    for (int j = 0; j < StaticVariables.supplyAreaList[i].LandList.Count; j++)
                    {
                        sumOfXP += StaticMethods.GetHatchCentroid(StaticVariables.supplyAreaList[i].LandList[j].Myhatch.Hatch).x * StaticVariables.supplyAreaList[i].LandList[j].LandLoadM;
                        sumOfYP += StaticMethods.GetHatchCentroid(StaticVariables.supplyAreaList[i].LandList[j].Myhatch.Hatch).y * StaticVariables.supplyAreaList[i].LandList[j].LandLoadM;
                        sumOfP += StaticVariables.supplyAreaList[i].LandList[j].LandLoadM;
                    }
                    gPoint loopstLocation = new gPoint(sumOfXP / sumOfP, sumOfYP / sumOfP);
                    Loopstation loopst = addLoopst(loopstLocation, sumOfP);
                    StaticVariables.supplyAreaList[i].LoopstationList.Add(loopst);
                    continue;
                }
                /////////////~~~~~~~~~


            
            }

        }

        public Loopstation addLoopst(gPoint point,double load)
        {
            vdInsert ins = new vdInsert();
            ins.SetUnRegisterDocument(vdFC.BaseControl.ActiveDocument);
            ins.setDocumentDefaults();
            ins.Block = vdFC.BaseControl.ActiveDocument.Blocks.FindName("MyLoopstationModel");
            //设置变电站的位置
            ins.InsertionPoint = point;
            ins.CreateDefaultAttributes();
            string loopstName ="环网站" + (StaticVariables.loopstationList.Count + 1);
            if (ins.Attributes.Count == 2)
            {
                ins.Attributes[1].ValueString = loopstName;
            }

            ins.Xscale = 25;
            ins.Yscale = 25;
            vdFC.BaseControl.ActiveDocument.Model.Entities.AddItem(ins);
            vdFC.BaseControl.ActiveDocument.Redraw(true);

            //Substation substation = new Substation("环网站", ins.InsertionPoint.x, ins.InsertionPoint.y, 0, 0, ins.Block, ins);
            //StaticVariables.substationList.Add(substation);
            Loopstation loopst=new Loopstation(loopstName,ins.InsertionPoint.x,ins.InsertionPoint.y,"环网站型号一",10,load,1000000);
            StaticVariables.loopstationList.Add(loopst);
            return loopst;
        }
        





    }
}


